Sub topic 5
Hoisting: What Happens Before Your Code Runs
This chapter assumes you already know the scope rules from the earlier chapters. Those chapters showed that var is scoped to the function and that let and const are scoped to the block. You should also be comfortable writing functions and reading try...catch blocks. Here we look at what the JavaScript engine does with your declarations before it runs any line of the scope that contains them.
The Two-Pass Model
The engine prepares a scope before it executes that scope. In the first pass it scans the scope's declarations and registers every name in the scope's environment. In the second pass it runs your statements from top to bottom.
People call this behavior hoisting because declarations act as if they were moved to the top of their scope. Nothing actually moves in your source code. The names already exist before execution starts. What differs between keywords is the initial state each name gets during the first pass.
| Declaration | Registered in first pass? | Initial state | Access before the declaration line |
|---|---|---|---|
| `var x` | Yes, in the function or global scope | `undefined` | Returns `undefined` |
| `function f() {}` | Yes | The full function | Works normally |
| `let x` / `const x` | Yes, in the block | Uninitialized | Throws `ReferenceError` |
var: Declared Early, Assigned Late
With var, only the declaration is hoisted. The assignment stays where you wrote it.
console.log(x); // undefined
var x = 5;
console.log(x); // 5The engine treats this as var x; at the top, with x = 5 left on line two. Because var ignores blocks, a var inside an if is hoisted to the top of the whole function:
function checkout(items) {
console.log(total); // undefined, not a ReferenceError
if (items.length > 0) {
var total = items.length * 10;
}
return total;
}
console.log(checkout([])); // undefined
console.log(checkout([1, 2])); // 20The empty cart returns undefined with no error. That silence is the main danger of var hoisting. A typo or an ordering mistake gives you a quiet undefined that spreads through your program, when you would want the program to fail at the line where the mistake is.
Function Declarations vs. Function Expressions
A function declaration is hoisted together with its body, so you can call it before the line where it appears. A function expression assigned to a variable follows that variable's rules.
console.log(greet('Ada')); // 'Hello, Ada'
function greet(name) {
return `Hello, ${name}`;
}
console.log(typeof shout); // 'undefined'
try {
shout('hi');
} catch (e) {
console.log(e.name); // 'TypeError'
}
var shout = function (msg) {
return msg.toUpperCase();
};Calling shout early throws a TypeError instead of a ReferenceError. The name shout exists and holds undefined, and undefined is not a function. If you see "x is not a function" for a function you clearly defined, check whether it is a var expression that runs too early.
let and const Are Hoisted Too
A common belief is that let and const are not hoisted. They are hoisted, but they start out uninitialized. This example shows the difference:
let color = 'blue';
function paint() {
try {
console.log(color);
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
let color = 'red';
}
paint();Suppose the inner let color were not hoisted. Then console.log(color) would find the outer variable and print 'blue'. It throws instead, because the first pass already registered an inner color that hides the outer one. That inner color cannot be read until its declaration line runs. The period between entering the scope and reaching the declaration has a name, the temporal dead zone. The next chapter covers it.
Common Mistakes
- Assuming
undefinedmeans "not declared." Withvar,undefinedcan mean the name is declared but has not been assigned yet. - Calling a
varfunction expression too early. This produces aTypeError, not aReferenceError. - Expecting an outer variable to show through before an inner
letorconst. The inner declaration hides the outer one for the entire block, including the lines above it.
Exercise
Predict the three lines this code logs, and explain each one. var a = 1; function test() { console.log(a); var a = 2; console.log(a); } test(); console.log(a);
Show answer
It logs undefined, then 2, then 1. Inside test, the inner var a is hoisted to the top of the function and starts as undefined, so it hides the global a, and the first log prints undefined. The assignment a = 2 then runs, so the second log prints 2. The global a was never touched, so the last log prints 1.
Exercise
Why does calling a function before a line like var run = function () {} throw a TypeError, while calling it before function run() {} works?
Show answer
A function declaration is hoisted with its body, so run already holds the function. With var, only the name is hoisted and it starts as undefined. The function is assigned only when that line runs. Calling undefined throws a TypeError.