2021-05-18
In JS, hoisting allows function, variables and classes be referenced before declared.
for example,
1myName("Amy");23function myName(name) {4 console.log("My name is " + name);5}67// My name is Amy8
var declaration is be hoisted, but initialization isn't !
The initial value of var is undefined .
see the example from mdn
1console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)2var num; // Declaration3num = 6; // Initialization4console.log(num); // Returns 6 after the line with initialization is executed.5
1console.log(num); // Returns 'undefined' from hoisted var declaration (not 6)2var num = 6; // Initialization and declaration.3console.log(num); // Returns 6 after the line with initialization is executed.4
1console.log(num); // Throws ReferenceError exception - the interpreter doesn't know about `num`.2num = 6; // Initialization3
If we doesn't declare num , it won't be hoisted.
There is hoisting action in let and const variable.
Unlike var, there's no default value of let and const hoisting.
1console.log(a) // ReferenceError: Cannot access 'a' before initialization2let a = 103
the func is called in TDZ1// (O)2// TDZ starts at beginning of scope3const func = () => console.log(letVar); // OK45let letVar = 3; // End of TDZ (for letVar)6func(); // Called outside TDZ!78// returns 39
1// (X) Exception !!!2// TDZ starts at beginning of scope3const func = () => console.log(letVar); // OK45// Within the TDZ letVar access throws `ReferenceError`6func(); // <--------- the function is called in TDZ7let letVar = 3; // End of TDZ (for letVar)89// Cannot access 'letVar' before initialization10
1// (X) Exception !!!2// TDZ starts at beginning of scope3 console.log(bar); // undefined4 console.log(foo); // ReferenceError5 var bar = 1;6 let foo = 2; // End of TDZ (for foo)78// Cannot access 'foo' before initialization9
1// (X) Exception !!!23var a = 104function test(){5 console.log(a)6 let a7}8test()910// Cannot access 'a' before initialization11