Sub topic 4
Hoisting: Calling Before Defining
This chapter assumes you know how var, let, and const differ, and that you have read the previous two chapters on function declarations and function expressions. The question here is practical: can you call a function on a line above the one where you defined it? The answer depends on which form you used.
Two Phases: Setup, Then Run
Before JavaScript runs any statement in a scope, it scans that scope and registers every declared name. This setup step is what people call hoisting. Nothing actually moves in your source code. Names simply exist before execution reaches their line.
Different declarations get different starting values during setup:
- A function declaration gets its full function body right away.
- A
varbinding gets the valueundefined. - A
letorconstbinding gets no value. It stays uninitialized until execution reaches its line. The stretch of time before that point is the temporal dead zone (TDZ).
Declarations Work Early
A function declaration can be called anywhere in its scope, including above its definition:
console.log(add(2, 3)); // 5
function add(a, b) {
return a + b;
}Expressions Follow Their Variable
A function expression is just a value assigned to a variable. Until the assignment line runs, the function does not exist. What you get before that point depends on the keyword.
With const or let, touching the name inside the TDZ throws a ReferenceError:
try {
multiply(2, 3);
} catch (e) {
console.log(e instanceof ReferenceError); // true
}
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(2, 3)); // 6With var, the name exists but holds undefined. Calling undefined throws a TypeError instead. This is a more confusing message, because it says the value "is not a function" rather than saying the name isn't ready yet:
console.log(typeof divide); // "undefined"
try {
divide(6, 2);
} catch (e) {
console.log(e instanceof TypeError); // true
}
var divide = function (a, b) {
return a / b;
};
console.log(divide(6, 2)); // 3| Form | Value after setup | Calling before the definition |
|---|---|---|
| `function f() {}` | The function | Works |
| `var f = function () {}` | `undefined` | `TypeError: f is not a function` |
| `let f = function () {}` | Uninitialized (TDZ) | `ReferenceError` |
| `const f = function () {}` | Uninitialized (TDZ) | `ReferenceError` |
The TDZ Is About Time, Not Position
A common misunderstanding is that a function body can never mention a const declared further down the file. It can. The TDZ ends when the declaration line executes, so the only thing that matters is when the reference is evaluated:
function report() {
return format(42);
}
const format = function (n) {
return `Value: ${n}`;
};
console.log(report()); // Value: 42This works because report is only called after format has been initialized. If you moved console.log(report()) above the const format line, it would throw a ReferenceError.
Common Errors
- Moving a declaration to an expression during a refactor. Code that used to call
init()at the top of a file starts throwing aReferenceErroronceinitbecomesconst init = function () {...}. - Reading the
varTypeError as a typo. "x is not a function" on avarexpression usually means an ordering problem, not a misspelled name. - Depending on hoisting for readability. Some teams like putting the main logic first and helper declarations below it. That is a valid style, but it only works with declarations.
Exercise
What does this code log, and why? console.log(typeof greet); var greet = function () { return 'hi'; }; console.log(typeof greet);
Show answer
It logs "undefined" and then "function". During setup, the var binding greet is created with the value undefined. The function expression is assigned only when the second line runs.
Exercise
The call start(); sits at the top of a file. Below it are function start() { return helper(); } and then const helper = function () { return 1; };. Does the call succeed?
Show answer
No. start is hoisted, so calling it works, but inside it helper is still in the temporal dead zone because its const line has not run yet. The call throws a ReferenceError.