Sub topic 5
Hoisting: What Happens Before Your Code Runs
This chapter assumes you can write and call functions, use if statements and for loops, and run code in Node.js or a browser console. It also assumes you have read the earlier chapters on function scope (var) and block scope (let and const). Hoisting only makes sense once you know which scope each declaration belongs to.
Hoisting is the name for a behavior that surprises many developers: you can sometimes use a variable or function on a line above the line that declares it. The code does not actually move. JavaScript processes your code in two passes, and declarations are handled in the first one. Once you understand those two passes, the odd results become predictable.
The Two Phases of Running a Scope
Every time JavaScript enters a scope, it works in two steps. The scope can be the whole script, a function call, or a block.
- Setup phase. The engine scans the scope for declarations (
var,let,const,function,class). It creates a binding for each one before any line runs. A binding is the link between a name and a storage slot. Each kind of declaration starts in a different state. - Execution phase. The engine runs your statements from top to bottom. Assignments put values into the bindings that already exist.
"Hoisting" describes the result of this process. Because the setup phase creates every binding first, a declaration acts as if it had been lifted to the top of its scope.
var: Hoisted and Initialized to undefined
A var declaration has two parts: the declaration (var x) and the optional initializer (= 5). Only the declaration is processed in the setup phase. The initializer runs later, when execution reaches that line.
console.log(x); // undefined
var x = 5;
console.log(x); // 5The engine treats this code as if it were written like this:
var x; // setup phase: binding created and set to undefined
console.log(x); // undefined
x = 5; // execution phase: the assignment happens here
console.log(x); // 5This is why reading a var before its declaration gives undefined and not an error. The binding already exists. It just has not received its value yet.
var Hoists to the Function, Not the Block
A var belongs to the nearest enclosing function, so its hoisting target is the top of that function, not the top of the block it appears in.
function check(flag) {
console.log(result); // undefined: result already exists here
if (flag) {
var result = 'set';
}
return result;
}
console.log(check(false)); // undefined
console.log(check(true)); // 'set'When flag is false, the if body never runs, yet result still exists for the whole function. The declaration was processed during setup. Only the assignment sits inside the if.
The Shadowing Trap
Hoisting causes a well-known bug when a local var has the same name as an outer variable:
var label = 'global';
function show() {
console.log(label); // undefined, not 'global'
var label = 'local';
console.log(label); // 'local'
}
show();Many developers expect the first console.log to print 'global', because the local label has not been "declared yet" on that line. But the setup phase of show has already created a local label set to undefined. That local binding shadows the outer one for the entire function body, including the lines above the declaration.
Function Declarations: Hoisted With Their Body
A function declaration starts with the function keyword as a statement. It is hoisted completely: during setup, the binding is created and set to the actual function object. You can call it before the line where it is written.
console.log(square(4)); // 16
function square(n) {
return n * n;
}This is intentional and useful. Many codebases put the main logic at the top of a file and helper function declarations below it.
Function Expressions Are Not Hoisted the Same Way
A function expression assigns a function to a variable. In that case, hoisting follows the rules of the variable's keyword, not the rules for functions. Arrow functions are always expressions.
try {
greet();
} catch (e) {
console.log(e.name); // 'TypeError'
}
var greet = function () {
return 'hi';
};
console.log(greet()); // 'hi'During setup, greet is a var binding set to undefined. Calling undefined() throws a TypeError ("greet is not a function"). The error is a TypeError and not a ReferenceError because the name exists. Its value just cannot be called.
If greet had been declared with let or const, the early call would throw a ReferenceError instead, for the reason covered next.
let, const, and class: Hoisted but Uninitialized
People often say that let and const "are not hoisted." That is not accurate. Their bindings are created during the setup phase of their block, like any other declaration. The difference is that they are left uninitialized. Reading or writing an uninitialized binding throws a ReferenceError.
You can show that the binding exists early with a shadowing example:
let level = 'outer';
{
try {
console.log(level); // does NOT fall back to the outer level
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
let level = 'inner';
console.log(level); // 'inner'
}If the inner let level were not hoisted, the first console.log would find the outer level and print 'outer'. It throws instead. The inner binding was created at the start of the block, and it shadows the outer one before it is initialized. The stretch of code between the start of the block and the declaration is called the temporal dead zone. The next chapter covers it in detail.
class declarations behave like let:
try {
new Point();
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
class Point {
constructor() {
this.x = 0;
}
}
console.log(new Point().x); // 0Summary of Hoisting Behavior
| Declaration | Binding created in setup? | Value before the declaration line runs | Scope it hoists to |
|---|---|---|---|
| `var x = 1` | Yes | `undefined` | Enclosing function (or script) |
| `let x = 1` | Yes | Uninitialized: access throws `ReferenceError` | Enclosing block |
| `const x = 1` | Yes | Uninitialized: access throws `ReferenceError` | Enclosing block |
| `function f() {}` | Yes | The full function | Enclosing function (block in strict mode) |
| `class C {}` | Yes | Uninitialized: access throws `ReferenceError` | Enclosing block |
| `var f = function () {}` | Yes, as a `var` | `undefined`: calling it throws `TypeError` | Enclosing function |
| `const f = () => {}` | Yes, as a `const` | Uninitialized: access throws `ReferenceError` | Enclosing block |
Edge Cases
A var and a Function With the Same Name
When a var and a function declaration share a name in the same scope, the function declaration sets the value during setup. The var declaration does not reset it to undefined. The var's initializer still runs later and overwrites it.
console.log(typeof value); // 'function'
var value = 1;
function value() {}
console.log(typeof value); // 'number'Code like this is confusing and easy to get wrong, and linters flag it. Knowing the rule still helps when you debug older code.
Function Declarations Inside Blocks
In strict mode, a function declared inside a block is scoped to that block. The same is true in ES modules and class bodies, which are always strict.
'use strict';
{
function inner() {
return 1;
}
console.log(inner()); // 1
}
console.log(typeof inner); // 'undefined'In sloppy mode, the specification has legacy compatibility rules (Annex B) that also make inner visible in the enclosing function after the block runs. Older engines handled this differently. If you need a function to exist outside a block, declare it outside the block. If you need it only inside, use strict mode or assign a function expression to a const.
Hoisting Happens Per Call
The setup phase runs every time a scope is entered. Each call to a function gets fresh var bindings set to undefined, and each pass through a block gets fresh let and const bindings. Values do not carry over from a previous call.
function counter() {
console.log(n); // undefined on every call
var n = 0;
n++;
return n;
}
counter(); // logs undefined, returns 1
counter(); // logs undefined, returns 1Common Errors and How to Read Them
| Symptom | Likely cause |
|---|---|
| A value is `undefined` even though the variable "has" a value further down | Reading a `var` before its assignment line runs |
| An outer variable unexpectedly reads as `undefined` inside a function | A local `var` with the same name shadows it from the top of the function |
| `TypeError: f is not a function` on an early call | `f` is a function expression assigned to a `var` |
| `ReferenceError: Cannot access 'x' before initialization` | Reading a `let`, `const`, or `class` binding before its declaration runs |
| `ReferenceError: x is not defined` | No binding with that name exists in any enclosing scope (a different problem from hoisting) |
The last two messages look similar but mean different things. "Cannot access before initialization" tells you that the binding exists and is hoisted, but you read it too early. "Is not defined" tells you that no declaration exists at all. That usually means a typo or a missing import.
Exercise
What does this program log, and why? var a = 'outer'; function run() { console.log(a); if (false) { var a = 'inner'; } console.log(a); } run();
Show answer
It logs undefined twice. The var a inside run is hoisted to the top of the function, even though it sits inside an if block that never runs. The local binding shadows the outer a and is set to undefined during setup. The assignment 'inner' never executes, so both reads see undefined.
Exercise
Two programs each call process() on their first line. In program 1, process is defined as function process() { return 1; }. In program 2, it is defined as const process = () => 1;. What happens in each, and what kind of error (if any) is thrown?
Show answer
Program 1 logs or returns 1, because a function declaration is hoisted together with its body. Program 2 throws a ReferenceError ("Cannot access 'process' before initialization"). The const binding exists from the start of the scope but stays uninitialized until its declaration line runs. If program 2 had used var instead of const, the call would throw a TypeError, because the var binding would hold undefined, which cannot be called.
Exercise
Explain how this code shows that let declarations are hoisted, even though reading them early throws an error. let mode = 'dark'; { console.log(mode); let mode = 'light'; }
Show answer
The console.log throws a ReferenceError instead of printing 'dark'. If the inner let mode were not hoisted, the lookup would skip the block and find the outer mode. The inner binding is created at the start of the block during the setup phase, so it shadows the outer variable right away. It stays uninitialized until its declaration runs, which is why the read throws.