What is the temporal dead zone (TDZ)?

The temporal dead zone is the period between the start of a scope and the line where a let, const or class is declared; the binding already exists (it is hoisted) but is uninitialised, so any access during that period throws a ReferenceError.

Why it exists

With var, reading a variable before its declaration silently gives undefined, which hides bugs. The TDZ turns these mistakes into immediate, clear errors. It also makes const meaningful: a constant can never be observed in an "unassigned" state.

"Temporal", not positional

The TDZ is about when code runs, not where it is written. A function can reference a let declared below it, as long as the function is called after the declaration has executed.

Places the TDZ shows up

  • Using a variable before its let/const line in the same scope.
  • Shadowing: an inner let x puts x in the TDZ for the whole inner block, so even reading the outer x there throws.
  • Default parameters referring to later parameters: function f(a = b, b = 1).
  • Classes: using a class before its declaration, and extends expressions that reference the class being defined.
  • typeof is not safe here: typeof x throws in the TDZ (unlike for undeclared variables).
  • Modules with circular imports: importing a binding that has not been initialised yet throws.

Practical advice

Declare variables at the top of their scope or right before first use, avoid relying on hoisting, and lint for no-use-before-define.

Code example

js
1// 1. Basic TDZ
2try {
3 console.log(total);
4} catch (e) {
5 console.log(e.name); // ReferenceError
6}
7let total = 10;
8
9// 2. Temporal, not positional: the function runs after the declaration
10function showLimit() {
11 return limit;
12}
13const limit = 5;
14console.log(showLimit()); // 5
15
16// 3. Shadowing puts the inner name in the TDZ for the whole block
17const theme = "dark";
18{
19 try {
20 console.log(theme); // refers to the INNER theme, which is still in the TDZ
21 } catch (e) {
22 console.log("shadowed:", e.name); // shadowed: ReferenceError
23 }
24 const theme = "light";
25}
26
27// 4. typeof is not safe in the TDZ (but is for undeclared names)
28console.log(typeof neverDeclared); // "undefined"
29try {
30 typeof later;
31} catch (e) {
32 console.log("typeof:", e.name); // typeof: ReferenceError
33}
34let later = 1;
35
36// 5. Default parameters are evaluated left to right
37function range(start = end - 5, end = 10) {
38 return [start, end];
39}
40try {
41 range(undefined, 10); // still throws: `end` is uninitialised while `start`'s default runs
42} catch (e) {
43 console.log("default param:", e.name); // default param: ReferenceError
44}
45const range2 = (end = 10, start = end - 5) => [start, end]; // refer only to EARLIER params
46console.log(range2()); // [5, 10]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app