let and const hoisting

Is there variable hoisting for let or const in JavaScript? Is it to put the variable in the TDZ area?

The way I choose to think about it is the following:

Variables have three "stages": declaration (it exists in the scope), initialization (you can reference it, and it has the value undefined), assignment (it has whatever value the code assigns to it).

var x = 3 hoists the declaration and initialization to the top of the current function's scope, and leaves the assignment (x = 3) where it is.

let and const hoist the declaration to the top of the current block's scope, but leave both the initialization and the assignment where it is.

The TDZ is the gap between declaration and initialization.

To be specific, if const and let did not hoist the declaration at all, then the following code would log 3 - if it hoisted the declaration and the initialization, there'd be no TDZ, and it would log 2. Because it hoists the declaration but not the initialization, it throws a reference error.

const a = 3; { console.log(a); const a = 2; }

(I'm sure many people may have a different mental model, or may disagree with this one; this is the one I hold and how I explain the concepts to newcomers).

4 Likes

Thank you for your answer. With your help, I understand