See the Pen thecodelog.com - ES6 Variables 1 by Deano (@deangilewicz) on CodePen.
Initializing:
Variable initialization refers to the process of storing a value in the variable. A variable may be initialized either at the time of its declaration or at a later point in time (except for const).
See the Pen thecodelog.com - ES6 Variables 2 by Deano (@deangilewicz) on CodePen.
Temporal Dead Zone:
It is possible to access a var variable in the following way:
See the Pen thecodelog.com - ES6 Variables 3 by Deano (@deangilewicz) on CodePen.
But with const and let variable declarations you cannot access a variable before it has been defined
See the Pen ES6 Variables 4 by Deano (@deangilewicz) on CodePen.
Updating:
It is possible to reassign values to var and also redeclare the variable.
See the Pen thecodelog.com - ES6 Variables 5 by Deano (@deangilewicz) on CodePen.
It is possible to reassign values to let but it is not possible to redeclare the variable.
See the Pen thecodelog.com - ES6 Variables 6 by Deano (@deangilewicz) on CodePen.
It is not possible to reassign values to const or redeclare the variable.
See the Pen thecodelog.com - ES6 Variables 7 by Deano (@deangilewicz) on CodePen.
Scope:
Scope is a term that is used to identify where variables are available to your program. The var, let, and const keywords scopes the variable to its enclosing function.
See the Pen thecodelog.com - ES6 Variables 8 by Deano (@deangilewicz) on CodePen.
However, the var keyword will leak the variable out of a block.
See the Pen thecodelog.com - ES6 Variables 9 by Deano (@deangilewicz) on CodePen.
let and const variables are block scoped.
See the Pen thecodelog.com - ES6 Variables 10 by Deano (@deangilewicz) on CodePen.
This means that each block represents its own scope.
See the Pen thecodelog.com - ES6 Variables 11 by Deano (@deangilewicz) on CodePen.
To ensure your var variable declaration does not leak into the global scope you can put it inside an IIFE. Below the “name” variable is scoped to the function that ensures the window name property does not get overridden since the “name” variable here is scoped to the function and does not leak.
See the Pen thecodelog.com - ES6 Variables 12 by Deano (@deangilewicz) on CodePen.
With const and let to avoid these variable declarations from leaking you can enclose them in a block.
See the Pen thecodelog.com - ES6 Variables 13 by Deano (@deangilewicz) on CodePen.
Loops:
Compared to var, let allows for scoping in each iteration of a loop.
See the Pen thecodelog.com - ES6 Variables 14 by Deano (@deangilewicz) on CodePen.
Immutability:
const does not mean immutable.
See the Pen thecodelog.com - ES6 Variables 15 by Deano (@deangilewicz) on CodePen.
The freeze method can be used to ensure properties of an object are immutable. However, this only works for shallow objects (top level).
See the Pen thecodelog.com - ES6 Variables 16 by Deano (@deangilewicz) on CodePen.