Variable Declaration
To function, a program must keep values in memory: they are stored in variables. There are 3 ways to declare a variable: with the keyword var
, and since ES6, with the keywords let
and const
.
To keep it simple, we will always use const
. If you really want to know the differences:
A variable declared with the keyword var
will have function scope, and will be accessible before its declaration in the code (but its value before initialization will necessarily be undefined
).
A variable declared with the keywords let
or const
will have block scope: a set of instructions separated by curly braces {
and }
. These variables will not be accessible before their declaration, unlike those declared with var
.
The difference between let
and const
is that a variable declared with const
cannot be reassigned:
console.log(first) // undefined
let first
console.log(first) // undefined
first = null
console.log(first) // null
console.log(firstBis) // undefined
var firstBis = 'bis'
console.log(firstBis) // 'bis'
// Illustration of the TDZ
// console.log(second) // Would cause a ReferenceError: we are in the TDZ of second!
let second
console.log(second) // undefined
second = 'two'
console.log(second) // 'two'
second = 2
console.log(second) // 2
// console.log(third) // Would cause a ReferenceError: we are in the TDZ of third!
const third = 3
console.log(third) // '3'
third = 4 // TypeError: cannot reassign a variable declared with const
third++ // TypeError: incrementing also corresponds to reassignment