CodePark/ questions / Scope & hoisting
START PRACTICINGPRACTICE
Frontend question · JavaScript › Scope & hoisting

Explain hoisting and the temporal dead zone (TDZ).

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.
  • var is hoisted and set to undefined, so reading it early gives undefined.
  • let, const and class are 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 var variables start as undefined.
  • Reading let, const or class inside the temporal dead zone (TDZ) throws a ReferenceError.
  • The TDZ depends on the order the code runs, not on where the code is written.