0

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

enter image description here

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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
ch_anvesh
  • 1
  • 1
  • If you don't explicitly provide an initial value (`let foo = value;`) then the variable is still initialized to `undefined` (just not at "hoisting time", like `var` would be). You are accessing `test1` *after* it was declared. – Felix Kling Sep 11 '20 at 19:19
  • `let test1` instantiates test1 with undefined, but it *is* defined, which is why there is no reference error for being not defined. Not being defined, and the value `undefined` are two different things. – Travis J Sep 11 '20 at 19:21
  • 1
    There are a lot of posts about hoisting, the temporal dead zone, and `let`, `const`, etc.; Here are a couple that should be read to begin understanding: [Are variables declared with let or const hoisted?](https://stackoverflow.com/q/31219420/215552), [What is the temporal dead zone?](https://stackoverflow.com/q/33198849/215552) – Heretic Monkey Sep 11 '20 at 19:21

0 Answers0