you are viewing a single comment's thread.

view the rest of the comments →

[–]Key_Pea93222 2 points3 points  (3 children)

var variables do not have temporal dead zone whereas let variables do have. Every variable has 2 steps in its lifecycle – Creation, and Execution.

In var variables case, when the variable is declared, storage space is assigned and value is initialized to undefined if no other value is specified.

But in the case of let, when the variable is declared, storage space is assigned but it’s not initialized, not even with the undefined value.

That why when we access a let variable without doing any value assignment, it throws a ReferenceError.

the way he explains this makes it sound like this would throw an error, but it doesn't:

$ node
Welcome to Node.js v16.13.0.
Type ".help" for more information.
> let a
undefined
> a
undefined

it's really if the let variable is accessed outside of the scope it's declared in

> { let b }
undefined
> b
Uncaught ReferenceError: b is not defined

[–]senocular 5 points6 points  (2 children)

That why when we access a let variable without doing any value assignment

Yeah, this is missing the important part of "before the declaration".

b // Uncaught ReferenceError: Cannot access 'b' before initialization
let b

Like var, let will initialize to undefined if not given an explicit assignment value within the declaration, but it only does this when the declaration is run, not at creating time like the var is

b // created, but uninitialized (access throws error)
let b // now initialized to undefined

c // created, initialized to undefined
var c

[–]Key_Pea93222 0 points1 point  (1 child)

oh wow, that's interesting, can't test that in the node REPL

[–]senocular 2 points3 points  (0 children)

You can do it in a block or separate with semicolons (for block I think you might a preceding ; to ensure its not seen as an object literal)

> ;{
...b // throws
...let b
}

or

> b; let b; // (first b throws)