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'isbeingdeclaredvarname='Marilyn';//thevariablenameisbeingdeclaredandassignedavalueatthesametimename='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'isdeclaredforfirsttimeconsole.log(name);//marilynname='Sophie';//nameisre-assignedconsole.log(name);//Sophievarname='Davina';//nameisredeclaredandanewvalueisalsoassignedtoitconsole.log(name);//Davinalet
let means the variable can only be declared once, but you can re-assign it multiple times
letname='Marilyn';console.log(name);//marilynname='Sophie';console.log(name);//Sophieletname='Davina';console.log(name);//SyntaxError:Identifier'name'hasalreadybeendeclaredWe 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);//marilynname='Sophie';console.log(name);//TypeError:Assignmenttoconstantvariable.