Hoisting and TDZ(Temporal Dead Zone)
in Programming on Javascript
Javascript ES6,ES7,ES8
There are two different codes.
1.
var myName = "nico";
console.log(myName);
// result = nico
2.
console.log(myName);
var myName = "nico";
// result = undefined
first sentence makes sense.
In case of number 2, we expect that we will have an error.
but the result is undefined. why?
because all Variable become “Hoisting”. so what is “Hoisting”?
Below code is same as number 2.
var myName;
console.log(myName);
myName = "nico";
// result = undefined
Hoisting helps to move Variable declaration to top of the code.
That’s why we would better to use let or const instead of var.
if we use ‘let’ instead of ‘var’ code will be like..
and we can find the error result. why?
console.log(myName);
let myName = "nico";
// result = uncaught reference error: myName is not defined
let also have hoisting but let has TDZ(Temporal Dead Zone)
and nobody can access before myName bind with a value
let myName;
console.log(myName);
myName = "nico"; //after this line, we can access myName
// result = uncaught reference error: myName is not defined
code after hoisting will be the same as var’s case.