Sub topic 4
Hoisting: Calling Before Defining
This chapter assumes you know how to write function declarations and function expressions, and that you understand the difference between var, let, and const. It explains why you can sometimes call a function on a line above its definition and sometimes cannot, and what error you get in each case.
"Hoisting" is the common name for what happens when JavaScript sets up a scope before running any code in it. The engine does not physically move code to the top of the file. Before running the body of a script, module, or function, it scans for declarations and creates a binding for each one. A binding is the link between a name and its value in a scope. What differs between declaration kinds is the state each binding starts in.
The Two Phases of a Scope
When the engine enters a scope, it works in two steps:
- Setup. It finds every declaration in the scope and creates a binding for each name. Function declarations are fully initialized now, with their bodies.
varbindings are initialized toundefined.let,const, andclassbindings are created but left uninitialized. - Execution. It runs the statements top to bottom. When it reaches a
letorconstline, it initializes that binding with the value. When it reaches avar x = ...line, it assigns the value to a binding that already exists.
The table summarizes what each binding holds before its line runs.
| Declaration form | Binding created at setup | Value before its line runs | Calling it early gives |
|---|---|---|---|
| `function f() {}` | Yes | The full function | It works |
| `var f = function () {}` | Yes | `undefined` | `TypeError: f is not a function` |
| `let f = function () {}` | Yes | Uninitialized (TDZ) | `ReferenceError: Cannot access 'f' before initialization` |
| `const f = () => {}` | Yes | Uninitialized (TDZ) | `ReferenceError: Cannot access 'f' before initialization` |
| No declaration at all | No | None | `ReferenceError: f is not defined` |
The error messages above are the ones V8 (Chrome and Node.js) prints. Other engines word them differently, but the error types are the same.
Function Declarations Are Hoisted With Their Bodies
A function declaration gets its name and its body during setup. Any code in the same scope can call it, including code written above it.
console.log(add(2, 3)); // 5
function add(a, b) {
return a + b;
}
try {
multiply(2, 3);
} catch (e) {
console.log(e instanceof ReferenceError); // true
}
const multiply = function (a, b) {
return a * b;
};The call to add works because add already holds a function when line 1 runs. The call to multiply fails because the const binding exists but has no value yet.
This behavior lets you put the main logic at the top of a file and the helper functions below it. It also makes mutual recursion between declarations work regardless of order:
console.log(isEven(10)); // true
function isEven(n) {
return n === 0 ? true : isOdd(n - 1);
}
function isOdd(n) {
return n === 0 ? false : isEven(n - 1);
}Both isEven and isOdd exist before the first console.log runs, so neither one depends on which is written first.
Function Expressions Follow Their Variable's Rules
A function expression is a value, so it is hoisted the way its variable is hoisted. The function itself is not created until the assignment line runs. Arrow functions behave the same way, because they are also expressions assigned to a variable.
With `var`: a `TypeError`
A var binding starts as undefined. Reading it early gives undefined, and calling undefined throws a TypeError.
console.log(typeof greet); // "undefined"
try {
greet();
} catch (e) {
console.log(e.name); // TypeError
}
var greet = function () {
return 'hi';
};
console.log(greet()); // hiThis is the hardest case to debug. The name exists, so you do not get a "not defined" error. You get "greet is not a function", which can look like the function was overwritten or misspelled.
With `let` or `const`: the temporal dead zone
The temporal dead zone (TDZ) is the period between the start of a scope and the line where a let, const, or class binding is initialized. Any read or write of the binding during that period throws a ReferenceError. Even typeof, which normally never throws, throws inside the TDZ:
try {
typeof later;
} catch (e) {
console.log(e.name); // ReferenceError
}
let later = 1;
console.log(typeof later); // "number"Compare this with a name that is never declared anywhere: typeof neverDeclared returns "undefined" and does not throw. The TDZ error exists to tell you that the name is declared in this scope and you reached it too soon.
The diagram shows the lifecycle of a let or const binding.
"Temporal" Means Time, Not Position
The TDZ depends on when code runs, not on where it is written. A function written above a const can still use that const, as long as the function is called after the const line has run.
function showLabel() {
return label;
}
// Calling showLabel() here would throw a ReferenceError.
const label = 'ready';
console.log(showLabel()); // readyThe reference to label inside showLabel is only resolved when showLabel runs. By then label is initialized. This is why code like the following is safe, even though handler mentions config before the config line:
const handler = () => config.retries;
const config = { retries: 3 };
console.log(handler()); // 3The rule to remember: defining a function that refers to a later binding is fine. Calling it before that binding is initialized is the error.
Name Collisions Between Declarations and `var`
When a function declaration and a var share a name in the same scope, the function declaration sets the binding's value at setup. The var declaration does not reset it to undefined. Later, the var assignment overwrites it.
console.log(typeof value); // "function"
var value = 42;
function value() {}
console.log(typeof value); // "number"Two function declarations with the same name in the same scope do not throw either. The last one wins, and it wins for every call in the scope, including calls above both declarations:
console.log(speak()); // second
function speak() {
return 'first';
}
function speak() {
return 'second';
}This is a common source of confusing bugs in large files that use only var and declarations. let, const, and class do not allow it. Declaring the same name with let and function in the same scope is a SyntaxError, which the engine reports before running any of the script.
Common Errors and How to Read Them
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot access 'x' before initialization` | Calling a `const`/`let` function, or a function that uses one, before its line runs | Move the call below the definition, or convert the function to a declaration |
| `x is not a function` and `x` is declared with `var` | Calling a `var` function expression before the assignment | Same as above. Also prefer `const` so the mistake becomes a clearer error |
| `x is not defined` | The name is not declared in any reachable scope | Check spelling, imports, and scope |
| A function returns the wrong behavior and nothing throws | A later declaration with the same name replaced it | Rename one of the functions, or switch to `const` so the duplicate becomes a `SyntaxError` |
A frequent version of the first error happens at module startup: a top-level call runs a declared function, and that function reads a const defined further down the file.
init(); // throws: Cannot access 'settings' before initialization
function init() {
console.log(settings.mode);
}
const settings = { mode: 'dark' };The declaration init is hoisted, so the call itself is allowed. The settings binding inside it is still in the TDZ. Moving init() to the end of the file fixes it.
Practical Guidance
- If you want to call helpers before they appear in the file, use function declarations. This is a reasonable style choice for files that read top-down.
- If you want the order of definitions to be enforced, use
constwith function expressions or arrows. An early call fails loudly with a clearReferenceError. - Avoid
varfor functions. It turns ordering mistakes into vagueTypeErrors and allows silent redeclaration. - When a startup
ReferenceErrornames a variable that is clearly defined, look for a call that runs before that variable's line, often through a hoisted declaration.
Exercise
What does this code log, and why? console.log(typeof a, typeof b); var a = function () {}; function b() {}
Show answer
It logs "undefined function". The var binding a exists after setup but holds undefined until its assignment line runs. The function declaration b is initialized with its body during setup, so typeof b is "function".
Exercise
This code throws a ReferenceError. Which line throws, and what is the smallest change that fixes it without changing const to var? const total = sum(1, 2); const sum = (x, y) => x + y; console.log(total);
Show answer
The first line throws, because sum is still in the temporal dead zone when it is called. Swap the first two lines so sum is initialized before the call. Converting sum to a function declaration, function sum(x, y) { return x + y; }, also works because the declaration is hoisted with its body.
Exercise
Does this code throw? Explain using the meaning of "temporal" in temporal dead zone. const getMax = () => limit * 2; const limit = 10; console.log(getMax());
Show answer
It does not throw. It logs 20. The arrow refers to limit, but that reference is only resolved when getMax is called. The call happens after the line const limit = 10 has run, so limit is initialized. The TDZ depends on when code runs, not on where the reference is written.