Catalog My learning Blog
Frontend Developer Course: 100 Concepts in 100 Days · Phase 4 · Lesson 32 · 5 min read

JavaScript Hoisting, Scope and Temporal Dead Zone

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: The Loop Closure Bug and Its Fix
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain lexical scope and the scope chain, the differences between var, let and const, how hoisting affects declarations and functions, why the temporal dead zone exists, and how module scope and block scope prevent accidental globals and shared state bugs.

Concept Explanation

Scope determines where a name is visible. JavaScript uses lexical scope, meaning that visibility is decided by where code is written, not by where it is called from. When a name is used, the engine looks in the current scope, then the enclosing scope, then the next one out, up to the module or global scope. This chain of scopes is fixed when the code is written, and it is what makes closures possible (Day 33).

There are three ways to declare variables and they scope differently. var is function scoped: a var declared inside an if block or a for loop is visible throughout the whole function. let and const are block scoped: they exist only within the nearest pair of braces. const additionally prevents reassignment of the binding, though it does not make the value immutable, so a const array can still be pushed to. Modern code uses const by default, let when reassignment is needed, and var essentially never.

Hoisting describes how declarations are processed before code runs. Function declarations are hoisted completely, so you can call them before the line where they appear. var declarations are hoisted and initialized to undefined, so reading a var before its assignment gives undefined rather than an error, which hides bugs. let, const and class declarations are hoisted too, but they are not initialized. From the start of the block until the declaration is evaluated, the variable is in the temporal dead zone, and touching it throws a ReferenceError. That error is a feature: it turns a silent undefined into a loud mistake.

The classic var bug involves loops and asynchronous callbacks. A for loop with var shares one variable across all iterations, so callbacks scheduled inside the loop all see its final value. With let, each iteration gets a fresh binding, so each callback sees the value from its own iteration. This single change fixed countless event handler bugs when let arrived in 2015.

Scripts and modules also differ. In a classic script, top-level var declarations and function declarations become properties of the global object, window in browsers, where any other script can read or overwrite them. ES modules have their own module scope: top-level declarations are private unless exported, and modules run in strict mode, where assigning to an undeclared variable throws instead of silently creating a global. This is one of many reasons to write every new file as a module (Day 38).

DeclarationScopeHoisting behaviorReassign
varFunctionHoisted, initialized to undefinedYes
letBlockHoisted, temporal dead zone until declaredYes
constBlockHoisted, temporal dead zone until declaredNo, but contents can change
function declarationFunction or blockFully hoisted, callable earlyYes
classBlockTemporal dead zoneYes
Module top levelModulePrivate unless exportedNot applicable

Worked Example: The Loop Closure Bug and Its Fix

Three buttons each log their index when clicked. The var version logs the same number for every button.

JavaScript
const buttons = document.querySelectorAll('.tab-button');   // three buttons

// Buggy: one shared i for the whole loop
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', () => console.log('var', i));
}
// Clicking any button logs: var 3

// Fixed: let creates a new binding per iteration
for (let j = 0; j < buttons.length; j++) {
  buttons[j].addEventListener('click', () => console.log('let', j));
}
// Clicking buttons logs: let 0, let 1, let 2

// Hoisting and the temporal dead zone
console.log(typeof hoistedFn);   // 'function': fully hoisted
console.log(legacy);             // undefined: var hoisted and initialized
try {
  console.log(modern);           // ReferenceError: in the temporal dead zone
} catch (e) { console.log(e.name); }

function hoistedFn() {}
var legacy = 'old';
let modern = 'new';

// const prevents reassignment, not mutation
const cart = [];
cart.push({ sku: 'A1' });        // fine
// cart = [];                    // TypeError: assignment to constant variable

// Block scope keeps temporary values local
if (cart.length) {
  const total = cart.length * 10;
  console.log(total);
}
// console.log(total);           // ReferenceError: total is not defined here

The var loop bug and the TDZ error both disappear once let and const are the only declarations in a codebase, which is why linters such as ESLint include a no-var rule.

var is function scoped and hoisted as undefined, so loop callbacks share one variable. let and const are block scoped and sit in the temporal dead zone until declared, so early access throws and each loop iteration gets its own binding.
var is function scoped and hoisted as undefined, so loop callbacks share one variable. let and const are block scoped and sit in the temporal dead zone until declared, so early access throws and each loop iteration gets its own binding.

Real-World Examples

  • ES2015, also called ES6, introduced let and const largely to fix var's function scoping and hoisting surprises, and the ESLint rules no-var and prefer-const are enabled in most popular shared configurations today.
  • Before modules, large sites suffered from global variable collisions between scripts, which is why libraries such as jQuery offered noConflict and why patterns such as the immediately invoked function expression, or IIFE, were used to create private scopes.
Key TakeawaysJavaScript scope is lexical: it is decided by where code is written, and every variable lookup is resolved by walking up the scope chain. Use const by default and let when reassigning; avoid var, which is function scoped and silently hoisted as undefined. let and const sit in a temporal dead zone until declared, which turns use-before-declaration into an error. Write modules, which have private top-level scope and strict mode.

Review Questions & Answers

The period between the start of a block and the evaluation of a let, const or class declaration in it. The binding exists but is uninitialized, and any access throws a ReferenceError, which surfaces use-before-declaration bugs that var would hide as undefined.

var is function scoped, so the whole loop shares one variable. The callbacks run later, after the loop has finished, and read that single variable's final value. let creates a new binding for each iteration, so each callback closes over its own value.

No. const prevents reassigning the variable to a different value, but the object or array it refers to can still be changed. Object.freeze, which is shallow, or immutable update patterns are needed to prevent mutation.

Each module has its own scope, so top-level declarations are private unless explicitly exported, and modules run in strict mode, where assigning to an undeclared name throws instead of creating a global.