Hoisting means the engine registers every declaration in a scope before any code in that scope runs. Declarations act as if they were moved to the top. Nothing is really moved in your code.
The kinds of declaration differ in how they start:
- Function declarations are fully hoisted with their body, so you can call them before the line where they appear.
varis hoisted and set toundefined, so reading it early givesundefined.let,constandclassare hoisted but left uninitialized.
The temporal dead zone (TDZ) is the time from the start of the scope until a let, const or class declaration runs. Any access during that time throws a ReferenceError.
The TDZ is about time, not about position in the file. For example, a function can use a let variable that is declared below it. This works, as long as you call the function after the declaration line has run.
- The engine registers declarations when a scope is created, before the code runs.
- Function declarations are fully hoisted, including their body.
- Hoisted
varvariables start asundefined. - Reading
let,constorclassinside the temporal dead zone (TDZ) throws aReferenceError. - The TDZ depends on the order the code runs, not on where the code is written.
Read more
- Hoisting (MDN) (https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)developer.mozilla.org
- Variable scope, closure (https://javascript.info/closure)javascript.info