Javascript : Hoisting and the Temporal Dead Zone
In Javascript we can declare a variable by var keyword (ES5). But in ES6 we can declare a variable by let and const . As we have a lots a difference between var and let/const but Temporal Dead zone is one of them.
Let me put an example here
console.log(test);
var test;
test= "I'm a checking";
is equivalent to
var test;
console.log(test);
test= "I'm a checking";
will get the same result.
Let me put an example here
console.log(test);
var test;
test= "I'm a checking";
is equivalent to
var test;
console.log(test);
test= "I'm a checking";
will get the same result.
An indication of this behavior is that both examples will log undefined to the console. If var test; wouldn’t always be on the top it would throw a ReferenceError.
This behavior called hoisting applies to var and also to let/const. As mentioned above, accessing a var variable before its declaration will return undefined as this is the value JavaScript assigns when initializing it.
But accessing a let/const variable before its declaration will throw an error.
The period between entering the variable’s scope and reaching their declaration is called the Temporal Dead Zone – i.e. the period in which the variable isn’t accessible.
Comments
Post a Comment