Sub topic 7
Creation and Execution: Why Hoisting Happens
This chapter assumes you can declare variables with var, let, and const, write and call functions, and run snippets in Node.js or a browser console. It also builds on the earlier chapters about lexical scope and the scope chain. If you remember that every function and block can create its own scope, you are ready.
"Hoisting" usually gets explained as "declarations move to the top of their scope." That picture is close enough to predict some output. It cannot tell you why var gives undefined, why let throws, and why a function declaration works before its line. The real explanation is that the engine handles each scope in two passes: it sets up the scope first, then runs the code. This chapter covers that model. The chapters after it apply the model to var, to functions, and to the temporal dead zone.
Two Phases for Every Scope
When JavaScript is about to run a piece of code that has its own scope (a script, a module, a function call, or a block), it does not start at line one straight away. It first goes through a creation phase. Then it runs the execution phase.
- Creation phase: the engine scans the scope's code for declarations and creates a binding for each declared name in that scope's environment. A binding is the engine's internal slot that pairs a name with a value. Nothing in the code runs yet. No assignments happen and no functions are called.
- Execution phase: the engine runs the statements top to bottom. Assignments put values into bindings that already exist, and lookups walk the scope chain to find them.
The ECMAScript specification names these setup steps directly: GlobalDeclarationInstantiation, FunctionDeclarationInstantiation, and BlockDeclarationInstantiation. "Hoisting" is the informal name for what those steps do.
The Code Never Moves
No source text gets rearranged. Your var x = 5; stays where you wrote it. What happens is that the binding x already exists by the time execution reaches the first line. The assignment = 5 is a normal statement and runs only when execution gets to it.
So "hoisting" is a metaphor for a split. The declaration takes effect during the creation phase. The initializer (the = value part) runs during the execution phase.
Proof That the Engine Looks Ahead
If the engine only read code line by line, an error on line 3 could never stop line 1 from running. This script shows that it can:
console.log("start");
let a = 1;
let a = 2;Run it and "start" is never printed. You get SyntaxError: Identifier 'a' has already been declared right away. Before running anything, the engine parsed the whole script and tried to set up its bindings, and two let declarations of the same name in one scope are not allowed. The error is reported before the execution phase begins.
The engine also looks ahead at declarations that sit inside code that will never run:
function check() {
console.log(flag); // undefined
if (false) {
var flag = true;
}
console.log(flag); // undefined
}
check();The if (false) branch never executes, yet flag exists as a binding and holds undefined. During the creation phase the engine looks at declarations and ignores control flow. A var inside an unreachable branch still declares a function-scoped name.
What the Creation Phase Puts in Each Binding
The declaration kinds differ in the starting state of their bindings. This is the most important table in the hoisting part of the tutorial:
| Declaration | Scope it binds to | State after creation phase | Reading it before its line |
|---|---|---|---|
| `var x` | Nearest function, or script | Initialized to `undefined` | Gives `undefined` |
| `function f() {}` | Nearest function or script (block rules covered later) | Initialized to the full function object | Works: you can call it |
| Function parameter | The function | Initialized to the argument (or `undefined`) | Not applicable: parameters exist from the start |
| `let x` | Nearest block | Created but **uninitialized** | Throws `ReferenceError` |
| `const x` | Nearest block | Created but **uninitialized** | Throws `ReferenceError` |
| `class C {}` | Nearest block | Created but **uninitialized** | Throws `ReferenceError` |
All of these are hoisted, because the creation phase creates a binding for every one of them. They differ only in the state the binding starts in. An uninitialized binding exists, which is why it shadows outer variables, but the engine refuses to read it until its declaration line runs. The next three chapters go through each row in detail. For now the point is that a single mechanism produces all three behaviors.
A Fresh Creation Phase on Every Call
A function's creation phase happens when the function is called. Defining the function does not trigger it. Each call builds a new environment, which is why local variables don't leak from one call to the next:
function show() {
console.log(typeof helper, typeof count);
var count = 1;
function helper() {}
}
show(); // "function undefined"
show(); // "function undefined"On each call, the creation phase creates count as undefined and helper as a ready function object. Then the execution phase runs the console.log. The assignment count = 1 from the first call does not carry over, because the second call starts with a new environment.
Blocks work the same way on a smaller scale. Each time execution enters a { ... } block that contains let, const, or class declarations, a new block environment is set up with those names uninitialized.
Order Inside a Function's Creation Phase
Within one function, the setup happens in a fixed order, which explains some surprising results:
- Parameters are bound to the arguments.
- Function declarations are bound to their function objects, replacing a parameter of the same name.
varnames that don't exist yet getundefined. Avarwith the same name as an existing parameter or function does not reset it.let,const, andclassbindings are created uninitialized. In practice these live in a separate environment, so they cannot reuse a parameter's name. That is aSyntaxError.
Redeclaring a parameter with var therefore changes nothing:
function f(x) {
console.log(x); // 10
var x;
console.log(x); // 10
}
f(10);When a var and a function declaration share a name, the function wins during the creation phase, and the var assignment wins once it runs:
console.log(typeof value); // "function"
var value = 42;
function value() {}
console.log(typeof value); // "number"Trace it in phases. Creation: value is created, and the function declaration puts the function object in it. The var adds nothing because the name already exists. Execution: the first log sees a function. value = 42 runs and replaces it. The function declaration line does nothing at execution time, since its work was done in the creation phase. The second log sees a number.
Nested Functions Wait Their Turn
An inner function's body gets its own creation phase only when that inner function runs. The outer function's creation phase registers the inner function's name and nothing more:
function outer() {
function inner() {
console.log(missing);
}
console.log("outer ran");
return inner;
}
const fn = outer(); // "outer ran"
try {
fn();
} catch (e) {
console.log(e.name); // "ReferenceError"
}The reference to the undeclared missing is not an error when outer runs. It fails only when inner executes and the scope chain lookup comes up empty. Syntax errors behave differently: the parser checks the whole file up front, so a syntax error anywhere stops the file from running at all.
Common Misconceptions
| Belief | What actually happens |
|---|---|
| "The engine moves declarations to the top." | Source text stays put. Bindings are created before execution starts. |
| "`let` and `const` are not hoisted." | They are hoisted (bindings exist from the start of the block) but start uninitialized. |
| "Assignments are hoisted too." | Only declarations are processed early. `= value` runs in place. |
| "Unreachable declarations don't count." | The creation phase ignores control flow. A `var` in `if (false)` still exists. |
| "A function's locals are set up once, when it is defined." | Setup happens on every call, with a fresh environment each time. |
Reading Code in Two Passes
When you need to predict output, copy what the engine does:
- Pass one (creation): for the current scope, list every declared name. Write down its starting state:
undefined, a function object, or uninitialized. - Pass two (execution): go line by line. Update the list on each assignment. On each read, check the list, then outer scopes. Throw if you find an uninitialized binding, and throw if you find nothing at all.
- When a function is called or a block is entered, start a new list for it and repeat.
This two-pass reading will be applied to var, to function declarations and expressions, and to the temporal dead zone in the chapters that follow.
Exercise
Predict the three lines printed by this code and explain each using the creation and execution phases: function run(a) { console.log(a); var a = 2; console.log(a); function a() {} } run(1); console.log(typeof run);
Show answer
First line: the function a. In the creation phase, the parameter a is bound to 1, then the function declaration a replaces it with the function object, and var a adds nothing because the name exists. Second line: 2, because the execution phase runs a = 2. Third line: "function", because run is a global function declaration created in the script's creation phase.
Exercise
Why does this script throw a SyntaxError without printing "ready"? console.log("ready"); const limit = 5; var limit = 10;
Show answer
The engine parses the whole script and instantiates its declarations before running any statement. A const and a var with the same name in the same scope conflict, so declaration instantiation fails with a SyntaxError and the execution phase, including console.log("ready"), never starts.
Exercise
A function contains if (false) { var token = "x"; } and later reads token. A teammate expects a ReferenceError. What happens, and why?
Show answer
Reading token gives undefined. During the function's creation phase the engine creates bindings for every var declaration in the function body regardless of control flow, so token exists and starts as undefined. The assignment never runs because the branch is never taken.