30 min·intermediate

Lesson 5

Hoisting & the TDZ

Build a practical mental model for hoisting & the tdz and use it in working JavaScript.

By the end, you will be able to…

  • Explain hoisting & the tdz in your own words
  • Use hoisting & the tdz in a small program
  • Recognize and debug a common failure mode

Build the mental model

Function declarations are fully hoisted — usable before their line. let and const are hoisted too, but remain in a 'temporal dead zone' from the start of the scope until their declaration line, throwing if accessed early.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: function ReferenceError: Cannot access 'inTDZ' before initialization

Why this matters

Understanding the TDZ explains a confusing but very deliberate error message instead of leaving it as a mystery.

Real-world example

Refactoring tools and linters that warn about 'used before defined' are protecting you from exactly this hoisting behavior.

Common mistakes

  • Assuming let/const behave like var and return undefined before their line (they throw instead)
  • Relying on function hoisting to organize code in a confusing top-to-bottom order
  • Being surprised that var IS accessible (as undefined) before its declaration line

Try it yourself

Challenge

Reorder the code so the TDZ ReferenceError no longer occurs.

Practice

Knowledge check

What happens when you access a `let` variable before its declaration line?

Summary

Function declarations hoist fully; let/const hoist into a temporal dead zone that throws until initialized.