So, maybe you're thinking about the basic differences between var vs let and const : "const is only for reading, let is mutable and var is both" and that the only difference is that ES6 introduced const and let, and var is an old-school syntax.
Well, not at all.
Analyzing some examples
1.- Here, is evident that we can't call let value before declare it
favCoffee = 'espresso'
function showFavoriteCoffe() {
console.log(favCoffee)
}
showFavoriteCoffe() // Cannot access 'favCoffee' before initialization
let favCoffee
2.- That could change if we use var instead let:
favCoffee = 'espresso'
function showFavoriteCoffe() {
console.log(favCoffee)
}
showFavoriteCoffe() //espresso
var favCoffee
Yeah, maybe it looks like an extra power of var using.
This is called Hoisting a process that allows you to use variables before they are declare.
3.- Let's consider this other example:
console.log(favCoffee) // undefined
var favCoffee = 'americano'
Although, in this example var is also hoisting here we face with the TDZ.
Temporal Dead Zone
It is defined as the state where variables are inaccessible, although they are within in the scope, they have not been declared.
{
/* TDZ starts
.
.
. */
var favCoffee = 'expresso' // TDZ ends
console.log(favCoffee) // expresso
}
Thanks ES6*
So in hoisting process due to the TDZ, by default JS returns var value initialized as undefined
, but with let or const it returns an error specifying that the variables hasn't been declared. So this is very helpful to catch errors and forces you to avoid using variables before they are declared
//using var
favCoffee = 'expresso'
var favCoffee
console.log(favCoffee) // undefined
//using const
favCoffee = 'expresso'
const favCoffee
console.log(favCoffee) // uncaught ReferenceError: Cannot access 'favCoffee' before initialization
(and this is why is important to consider using reporter ruler like ESLint to avoid some mistakes when you are coding).
Conclusion
Hoisting is always there, so it is important to use let and const as far as you can, this avoid undefined
errors and let you catch them faster.
** ES6
Top comments (0)