I am learning JavaScript and having trouble understanding Temporal Dead Zone along with Hoisting. So tried the following example,
let test1;
console.log(test1);
console.log(test2);
let test2;
The output is as follows:
undefined
VM883:3 Uncaught ReferenceError: test2 is not defined
at <anonymous>:3:13
From my understanding, "Hoisting" feature creates memory space for all variables declarations (var, let, const, function, class). So I believe, both test1
and test2
are read and allocated space by the compiler.
From my understanding, "Temporal Dead Zone" is specific to let
& const
keywords and they're not initialized as "undefined" when they're just declared. So when we access it before initialization, we get a Reference error. Hence, both test1
and test2
should have thrown Reference error.
But why was the reference error thrown only for test2
? Since we have not declared both the variables, why was test1
logged as undefined?