Intermediate · 2 of 17 · 16 min read
Hoisting
What the engine does before your first line runs, why var gives undefined and let throws, and how to read any hoisting snippet.
- Hoisting
Before any code in a scope runs, the engine walks that scope and registers every declaration it finds. Hoisting is the name for the effects of that pass: a name can exist before the line that declares it.
Step through what that means, on a snippet that uses all three:
console.log(fn());
console.log(v);
console.log(l);
function fn() { return 'F'; }
var v = 1;
let l = 2;
The scope
| fn | function fn() {} |
|---|---|
| v | undefined |
| l | uninitialised — TDZ |
Console
- nothing yet
scan Before line 1 runs at all, the engine walks the scope and creates every binding it finds. Three names already exist, in three different states.
The scope
| fn | function fn() {} |
|---|---|
| v | undefined |
| l | uninitialised — TDZ |
Console
- F
1 fn() works. A function declaration is hoisted with its whole body, so it is callable above the line that defines it.
The scope
| fn | function fn() {} |
|---|---|
| v | undefined |
| l | uninitialised — TDZ |
Console
- F
- undefined
2 v logs undefined. The declaration was hoisted; the = 1 is still four lines away.
The scope
| fn | function fn() {} |
|---|---|
| v | undefined |
| l | uninitialised — TDZ |
Console
- F
- undefined
- ReferenceError: Cannot access 'l'
3 l throws. It was hoisted too — that is why it shadows anything outside — but it holds no value, so reading it is a ReferenceError, not undefined.
The scope
| fn | function fn() {} |
|---|---|
| v | 1 |
| l | uninitialised — TDZ |
Console
- F
- undefined
5 With line 3 removed, execution reaches var v = 1 and the binding finally gets its value. Nothing moved — the assignment simply ran.
The scope
| fn | function fn() {} |
|---|---|
| v | 1 |
| l | 2 |
Console
- F
- undefined
6 let l = 2 runs, and here is where the TDZ ends — at the declaration line, not at the top of the scope.
var gets undefined, and a let gets nothing at all — and “nothing at all” is what the Temporal Dead Zone is.The four behaviours
| Declaration | Registered before execution | Value before its line runs |
|---|---|---|
function f() {} |
yes | the complete function |
var x |
yes | undefined |
let / const |
yes | uninitialised — ReferenceError |
class C {} |
yes | uninitialised — ReferenceError |
console.log(typeof fn); // "function" — usable already
console.log(typeof v); // "undefined" — declared, not assigned
// console.log(typeof l); // ReferenceError: Cannot access 'l' before initialization
// console.log(typeof C); // ReferenceError
function fn() {}
var v = 1;
let l = 2;
class C {}
typeof is worth noting: it is the one operator that normally never throws, and the TDZ makes it
throw. That asymmetry is a favourite interview detail.
var: the declaration moves, the assignment does not
console.log(x); // undefined — not a ReferenceError
var x = 10;
console.log(x); // 10
The engine effectively sees:
var x; // hoisted to the top of the function scope
console.log(x); // undefined
x = 10; // the assignment stays where you wrote it
console.log(x); // 10
var is hoisted to the top of the function, not the block — which is the other half of why it is
avoided:
function f() {
if (true) {
var inside = 'visible';
}
for (var i = 0; i < 3; i++) {}
console.log(inside); // "visible" — the block did not contain it
console.log(i); // 3 — the loop variable outlived the loop
}
f();
Function declarations: the whole thing moves
This is why you can call a function defined at the bottom of a file:
greet(); // "Hello!" — works
function greet() {
console.log('Hello!');
}
A function expression is a var (or let) assignment, so only the variable is hoisted:
// greet(); // TypeError: greet is not a function
var greet = function () {
console.log('Hi!');
};
greet(); // "Hi!"
The error message is the tell. TypeError: greet is not a function means the name exists and holds
undefined. ReferenceError: greet is not defined means the name does not exist at all. Arrow
functions behave the same way, because they are also expressions:
// arrow(); // TypeError
var arrow = () => {};
// letArrow(); // ReferenceError — TDZ, a different error for a different reason
let letArrow = () => {};
| What you wrote | Calling it too early |
|---|---|
function f() {} |
works |
var f = function () {} |
TypeError: f is not a function |
var f = () => {} |
TypeError: f is not a function |
let f = () => {} |
ReferenceError: Cannot access 'f' |
| nothing | ReferenceError: f is not defined |
Functions are hoisted above var
When a name is declared both ways, the function wins the hoisting pass and the assignment still runs in place:
console.log(typeof thing); // "function" — the declaration won
var thing = 'a string';
console.log(typeof thing); // "string" — the assignment overwrote it
function thing() {}
A plain duplicate var with no assignment does not erase the value:
var a = 1;
var a;
console.log(a); // 1 — the second `var` is a no-op
Function declarations inside blocks
A function declaration inside a block is block-scoped in strict mode, which modules always are:
// in a module (strict)
{
function blocked() {}
}
// console.log(typeof blocked); // "undefined" in strict mode
In sloppy mode the behaviour is messy and historically inconsistent between engines. Declaring
functions inside an if is best avoided entirely — assign a function expression to a const
instead.
const handler = condition
? () => console.log('a')
: () => console.log('b');
handler();
Reading a snippet quickly
The procedure that answers every one of these questions:
- Find the scope — a function body, a block, or the module top level.
- List the declarations in it. Functions first, with their bodies. Then
var, asundefined. Thenlet/const/class, as uninitialised. - Read the lines in order, substituting those starting values.
function example() {
console.log(a); // step 2 says: var a exists, holds undefined
console.log(b()); // step 2 says: function b exists complete → "B"
var a = 1;
function b() { return 'B'; }
let c = 3;
console.log(a, c); // 1 3 — both lines have now run
}
example();
And the version that throws, so the difference is visible:
function broken() {
// console.log(c); // ReferenceError: Cannot access 'c' before initialization
let c = 3;
}
Why let and const exist
Hoisting with an undefined default lets a genuine mistake run silently:
function totalVar(items) {
console.log(total); // undefined — no complaint
var total = 0;
for (var i = 0; i < items.length; i++) total += items[i];
return total;
}
console.log(totalVar([1, 2])); // 3 — works, but the first line was a bug
function totalLet(items) {
// console.log(total); // ReferenceError — the mistake is reported
let total = 0;
for (const item of items) total += item;
return total;
}
console.log(totalLet([1, 2])); // 3
The TDZ is not a missing feature — it is the fix. Use const by default, let when you reassign,
and var never.
Common mistakes
Saying let is not hoisted
Mistake. Answering “only var is hoisted”.
Why it fails. let and const are registered in the same pass — that is precisely why the inner
name shadows the outer one and throws instead of reading it.
What to do instead. “All declarations are hoisted; let and const stay uninitialised until
their line runs, and that window is the TDZ.”
let outer = 'from above';
{
// console.log(outer); // ReferenceError — the inner `outer` is already in scope
let outer = 'from the block';
}
Expecting a ReferenceError from a function expression
Mistake. Reading greet() above var greet = function () {} as “not defined”.
Why it fails. The variable was hoisted and holds undefined, so the failure is calling
undefined — a TypeError.
What to do instead. Read the error type as information: TypeError means the name exists.
Relying on hoisting to order a file
Mistake. Calling functions above their declarations because “hoisting handles it”.
Why it fails. It works for function declarations and breaks the moment one is refactored into a
const arrow — a very common, very confusing change.
What to do instead. Define before use. Keep hoisting as something you can read, not something
you depend on.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
Hoisting decides what a name means before its declaration line has run.
What does this log?
console.log(x);
var x = 10;Not every way of defining a function is hoisted the same way.
What happens when this runs?
sayHi();
function sayHi() {
console.log("Hi");
}Which of these can you call on a line *above* where it is written?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.