Sub topic 8
Hoisting var Declarations
This chapter assumes you already know three things: how function scope works, what the scope chain is, and that every scope goes through a creation phase before its code runs. It covers exactly what happens to a var declaration during those two phases, and the bugs that come from that behavior.
The Short Version
When a scope is created, the engine scans it for var declarations. It creates a binding for each name it finds and sets that binding to undefined. The assignment part of the statement does not move. It runs only when execution reaches that line.
console.log(x); // undefined
var x = 5;
console.log(x); // 5The first line does not throw. A binding named x already exists when that line runs, because the creation phase made it. The value 5 is not there yet, because x = 5 has not executed.
"Hoisting" is a metaphor. Nothing in your source text actually moves. The engine registers the name before running any code, so the code behaves as if the declaration had been moved to the top of its scope.
A Mental Rewrite
One reliable way to predict var behavior is to rewrite the code the way the engine effectively sees it. Split each var name = value; into two parts. Put a declaration at the top of the enclosing function (or script), and leave a plain assignment where the original line was.
function original() {
console.log(total);
var total = 10;
console.log(total);
}
function rewritten() {
var total; // creation phase: binding exists, value is undefined
console.log(total);
total = 10; // execution phase: assignment happens here
console.log(total);
}
original(); // undefined, then 10
rewritten(); // undefined, then 10Both functions print the same output. If you can do this rewrite in your head, most var puzzles become mechanical.
What Gets Hoisted and What Does Not
| Part of the statement | Handled in creation phase? | Handled in execution phase? |
|---|---|---|
| The name (`var total`) | Yes, binding created | No, the statement is skipped as a declaration |
| Initial value `undefined` | Yes | No |
| The initializer expression (`= 10`) | No | Yes, evaluated when the line is reached |
| Side effects in the initializer (function calls, logging) | No | Yes, in source order |
The last row matters when the initializer does real work:
function loadConfig() {
console.log("loading config");
return { debug: true };
}
console.log("start", config); // start undefined
var config = loadConfig(); // "loading config" is logged here, not earlier
console.log("end", config); // end { debug: true }loadConfig is not called early. Only the name config exists early.
var Ignores Blocks
A var declaration is hoisted to the nearest enclosing function or to the top of the script. It is not hoisted to the nearest block. That means if, for, while, try, and bare { } blocks do not contain it.
function blocks() {
console.log(a, b, c); // undefined undefined undefined
if (true) {
var a = 1;
}
for (var b = 0; b < 2; b++) {}
{
var c = 3;
}
console.log(a, b, c); // 1 2 3
}
blocks();All three names belong to the function scope of blocks. The loop counter b is still visible after the loop and holds its final value, 2.
Hoisting Happens Even in Code That Never Runs
The creation phase reads declarations from the source, so it does not care whether a branch will execute. A var inside a branch that never runs still creates a binding.
function neverRuns() {
if (false) {
var ghost = "you will never see this";
}
console.log(ghost); // undefined
console.log(typeof ghost); // "undefined"
console.log("ghost" in globalThis); // false: it is local, not global
}
neverRuns();If you remove the var ghost line entirely, console.log(ghost) throws a ReferenceError. The dead branch changes the behavior of the code around it.
The Most Common Bug: A Hoisted var Shadows an Outer Name
This is the error that costs the most debugging time. A function reads an outer variable near its top. Later in the same function, someone adds a var with the same name. The hoisted local binding now shadows the outer one for the whole function, including the lines above the declaration.
var message = "hello from outside";
function report() {
console.log(message); // undefined, not "hello from outside"
if (Math.random() > 2) { // never true
var message = "local";
}
console.log(message); // undefined
}
report();When report runs, the scope chain lookup for message stops at the function's own binding, because the creation phase put one there. That binding holds undefined. The outer message is never consulted.
The rewrite makes this obvious:
var message = "hello from outside";
function reportRewritten() {
var message; // local binding shadows the outer one everywhere
console.log(message); // undefined
if (Math.random() > 2) {
message = "local";
}
console.log(message); // undefined
}
reportRewritten();Redeclaring with var
var allows the same name to be declared more than once in one scope. The repeated declarations collapse into a single binding. A declaration without an initializer does not reset the value.
var count = 1;
var count; // no effect: binding already exists
console.log(count); // 1
var count = 2; // acts as a plain assignment
console.log(count); // 2This rule is why copy-pasting a block of code that starts with var result = ... into a function that already has result silently overwrites data instead of failing. let and const would throw a SyntaxError for the same duplication, before any code runs.
var and Parameters with the Same Name
A parameter is already a binding in the function scope. A var with the same name reuses that binding. It does not reset the parameter to undefined.
function withParam(value) {
var value; // reuses the parameter binding
console.log(value); // whatever was passed in
var value = "changed";
console.log(value); // "changed"
}
withParam(42); // 42, then "changed"var at the Top Level of a Script
In a classic script (not a module), a top-level var creates a property on the global object, just as it did in the global scope chapter. Hoisting applies there too. The property exists, holding undefined, before the first line of the script runs.
// Run as a classic script in a browser console or with `node -e`
console.log("early" in globalThis); // true
console.log(globalThis.early); // undefined
var early = "set";
console.log(globalThis.early); // "set"In an ES module or a CommonJS file, top-level var is local to that module, so "early" in globalThis would be false. Module scope gets its own chapter later.
Why var Hoisting Is Rarely Useful on Purpose
Code almost never relies on reading a var before its declaration line. The behavior exists for historical reasons, and in practice it mostly hides mistakes. A read that should fail loudly returns undefined instead, and the error shows up somewhere further down the program.
These practices remove most var hoisting bugs:
- Use
constby default, andletwhen you need to reassign. Their hoisting behavior (covered in the temporal dead zone chapter) turns early reads into immediate errors. - If you must keep
varin older code, declare everyvarat the top of its function. Then the source matches what the engine does. - Turn on the ESLint rules
no-var,no-use-before-define, andno-redeclare. They catch the patterns in this chapter at lint time. - When refactoring legacy code from
vartolet, watch for code that depended on function-wide visibility, such as a loop counter read after the loop. Those reads will start throwing, which is usually the bug you wanted to find.
Edge Cases at a Glance
| Situation | Result |
|---|---|
| Read a `var` before its line | `undefined` |
| Read a name with no declaration anywhere | `ReferenceError` |
| `var` inside `if (false) { }` | Binding still created in the function |
| `var` inside a block or loop | Visible in the whole enclosing function |
| `var x;` after `var x = 1;` | Value stays `1` |
| `var p;` where `p` is a parameter | Parameter value kept |
| Top-level `var` in a classic script | Property on `globalThis`, hoisted as `undefined` |
| Top-level `var` in a module | Local to the module, not on `globalThis` |
Function declarations follow a different hoisting rule, since they are hoisted along with their bodies. That rule, and what happens when a function declaration and a var share a name, is the topic of the next chapter.
Exercise
Predict the three logged values, then explain why the first one is not "outer". var label = "outer"; function check(flag) { console.log(label); if (flag) { var label = "inner"; } console.log(label); } check(false); check(true);
Show answer
check(false) logs undefined, then undefined. check(true) logs undefined, then "inner". (That is four lines in total; the first three are undefined, undefined, undefined.) The var label inside check is hoisted to the top of the function and initialized to undefined during the creation phase, whether or not the if branch runs. That local binding shadows the outer label for the whole function, so the first read never reaches "outer".
Exercise
What does this print, and which line would you change to make the second log throw a ReferenceError instead? function tally() { for (var i = 0; i < 4; i++) {} console.log(i); var i; console.log(i); } tally();
Show answer
It prints 4, then 4. The loop's var i belongs to the function scope, so it survives the loop with its final value. The later var i is a redeclaration with no initializer, so it does not reset the value. Change the loop to for (let i = 0; i < 4; i++) {} and delete the standalone var i line. Then i exists only inside the loop, and both console.log(i) calls throw a ReferenceError. If you keep the var i line, the logs print undefined instead, because var i declares a separate function-scoped binding.
Exercise
Rewrite this function the way the engine effectively sees it after the creation phase, and state what it returns. function compute() { result = base * 2; var base = 5; var result; return result; }
Show answer
The rewritten form is: function compute() { var base; var result; result = base 2; base = 5; return result; }. When result = base 2 runs, base is undefined, so undefined * 2 gives NaN. The function returns NaN. The later var result; does not reset it, and assigning base = 5 afterward does not change result.