var, let, const

var, let and const are the three types of variables in JavaScript.

There are two concepts important to understand before looking at these three different types of variables.

Declaration: when a variable is declared, this is when it is named for the first time.

Assignment: this is when that variable is given a value.

A variable must always be declared before a value can be assigned to it. It is common to declare a variable and assign a value to it at the same time, as can be seen on line 3.

index.js
1
varname;//thevariable'name'isbeingdeclared
2
3
varname='Marilyn';//thevariablenameisbeingdeclaredandassignedavalueatthesametime
4
5
name='Sopihe'//thevariable'name'isbeingassigned.
6

var

Variables created using var can be re-declared many times and the value assigned to it can also be changed many times.

index.js
1
varname='Marilyn';//'name'isdeclaredforfirsttime
2
3
console.log(name);
4
//marilyn
5
6
name='Sophie';//nameisre-assigned
7
console.log(name);
8
//Sophie
9
10
varname='Davina';//nameisredeclaredandanewvalueisalsoassignedtoit
11
console.log(name);
12
//Davina
13

let

let means the variable can only be declared once, but you can re-assign it multiple times

index.js
1
letname='Marilyn';
2
3
console.log(name);
4
//marilyn
5
6
name='Sophie';
7
console.log(name);
8
//Sophie
9
10
letname='Davina';
11
console.log(name);
12
//SyntaxError:Identifier'name'hasalreadybeendeclared
13

We can see here that it is possible to give 'name' a new value (re-assigning) but you cannot re-declare it using the keyword.

const

const means the variable cannot be re-declared and a new value cannot be assigned to it.

You should use const for values you know will never change, like 24 hours in a day or 7 days in a week.

index.js
1
constname='Marilyn';
2
3
console.log(name);
4
//marilyn
5
6
name='Sophie';
7
console.log(name);
8
//TypeError:Assignmenttoconstantvariable.
9

Further reading

how var, const, let relates to lexical environment