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.
varname;//thevariable'name'isbeingdeclared
varname='Marilyn';//thevariablenameisbeingdeclaredandassignedavalueatthesametime
name='Sopihe'//thevariable'name'isbeingassigned.
var
Variables created using var can be re-declared many times and the value assigned to it can also be changed many times.
varname='Marilyn';//'name'isdeclaredforfirsttime
console.log(name);
//marilyn
name='Sophie';//nameisre-assigned
console.log(name);
//Sophie
varname='Davina';//nameisredeclaredandanewvalueisalsoassignedtoit
console.log(name);
//Davina
let
let means the variable can only be declared once, but you can re-assign it multiple times
letname='Marilyn';
console.log(name);
//marilyn
name='Sophie';
console.log(name);
//Sophie
letname='Davina';
console.log(name);
//SyntaxError:Identifier'name'hasalreadybeendeclared
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.
constname='Marilyn';
console.log(name);
//marilyn
name='Sophie';
console.log(name);
//TypeError:Assignmenttoconstantvariable.