Home >Web Front-end >JS Tutorial >Hoisting: facing Temporal Zenless Zone Zero
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.
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.
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 }
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).
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
The above is the detailed content of Hoisting: facing Temporal Zenless Zone Zero. For more information, please follow other related articles on the PHP Chinese website!