Hoisting in JavaScript
Before JavaScript runs the code in a script or a function, it scans that code for declarations and creates every variable and function they declare. The code then runs from the top. The effect is as if the declarations had been lifted, or hoisted, to the top of their scope, although nothing in the source actually moves.
What a name holds before its declaration line runs depends on how it was declared:
| Declaration | Before its line runs |
|---|---|
function declaration |
the whole function, ready to call |
var |
undefined |
let, const, class |
nothing yet: reading it throws a ReferenceError |
Function declarations
Section titled “Function declarations”A function declaration is hoisted together with its body, so it can be called from anywhere in its scope, even above the place it is written:
console.log(addTax(100));
function addTax(price) { return price * 1.2;}This prints:
120This is useful in practice, because a file can open with the main steps and keep the helper functions further down.
A var declaration is hoisted, but its value is not. The variable exists from the start of its scope and holds undefined until the assignment runs:
console.log(orderCount);var orderCount = 7;console.log(orderCount);This prints:
undefined7Because var is function-scoped, a var inside a block is hoisted to the top of the whole function, not of the block:
function checkout() { console.log(typeof total); if (true) { var total = 30; } console.log(total);}
checkout();This prints:
undefined30Function expressions
Section titled “Function expressions”A function expression is a value assigned to a variable, so it follows the rules of that variable rather than those of a function declaration. With var, the variable holds undefined until the assignment, and calling it early throws a TypeError:
try { formatPrice(4.5);} catch (err) { console.log(`${err.name}: ${err.message}`);}
var formatPrice = function (amount) { return `£${amount.toFixed(2)}`;};
console.log(formatPrice(4.5));This prints:
TypeError: formatPrice is not a function£4.50Arrow functions assigned to a variable behave the same way.
let, const and class
Section titled “let, const and class”let, const and class declarations are hoisted too, but the variable is left uninitialised until its declaration line runs. Reading it before then throws a ReferenceError:
try { console.log(stockLevel);} catch (err) { console.log(`${err.name}: ${err.message}`);}
let stockLevel = 12;console.log(stockLevel);This prints:
ReferenceError: Cannot access 'stockLevel' before initialization12The period before the declaration runs is called the temporal dead zone. Hoisting - var vs let looks at it in more detail.
The error is the safer behaviour, since a var read too early gives undefined and the program carries on with a wrong value. Declaring variables near the top of their scope, before any code uses them, avoids both problems.
Steve Griffith covers this topic in his video JavaScript Hoisting.