Hoisting: Using Things Before They Exist
JavaScript lets you use some things before they appear in your code. This is called hoisting, and it happens because of Phase 1 memory creation.
Function declarations are fully hoisted (stored with their code). Variables declared with var are hoisted as undefined. Function expressions and arrow functions behave like variables.
EXERCISE
1Why Can You Call a Function Before Writing It?
JavaScript has a surprising trick up its sleeve: you can sometimes use things before they appear in your code. This is called hoisting, and it happens because of Phase 1 (memory creation).
In most languages, using a name before the line that declares it is simply an error. In it sometimes works, sometimes gives you undefined, and sometimes throws. Which of the three you get is entirely predictable, and the rule comes from the memory phase you met in Unit 1: declarations are processed before any code runs, and what gets put in the slot depends on how the name was declared.
The word for this is hoisting. It is the single most common interview question about JavaScript, and it is also the reason a file can work when you move a function and break when you move a variable.
A function declaration can be called before it appears:
greet();
function greet() {
console.log("Hello!");
}
This prints Hello!. By the time the first line runs, greet already holds the complete function, because the memory phase stored it whole before execution started. Where the declaration sits in the file makes no difference at all.
A var behaves differently, and the difference is the whole lesson:
console.log(score); // undefined
var score = 100;
console.log(score); // 100
The first line does not throw. score exists, because the memory phase gave it a slot, but the slot is empty until execution reaches the assignment on line two. So you get undefined, a real value meaning "declared, nothing in it yet", rather than an error.
A name that was never declared anywhere is a third case again:
console.log(ghost); // ReferenceError: ghost is not defined
No declaration means no slot was ever created, so there is nothing to read. JavaScript distinguishes "I have this name and it is empty" from "I have never heard of this name", and it reports them differently. Reading undefined and catching a ReferenceError are therefore two different bugs with two different fixes, and telling them apart quickly is worth the few minutes this lesson takes.
Pro Tip: Nothing is physically moved to the top of the file. The phrase "hoisted" makes it sound like the engine rewrites your code, and it does not. Declarations are simply processed in an earlier pass than the statements that read them.
EXERCISE
2Function Declarations vs Function Expressions
Not all functions are created equal when it comes to hoisting. The way you define a function changes whether it gets hoisted or not.
Not every function is hoisted, and the difference comes down to how you wrote it rather than what it does. This catches people out because both forms produce a callable function, look similar on the page, and behave identically once execution has passed them. The difference only shows up when something calls them early.
A function declaration starts with the function keyword at the beginning of the statement. It is stored complete during the memory phase, so it is callable from anywhere in its scope:
sayHi(); // "Hi there!"
function sayHi() {
console.log("Hi there!");
}
A function expression assigns a function to a variable. The variable is what gets declared, so the variable's rule applies, not the function's:
sayBye(); // TypeError: sayBye is not a function
var sayBye = function () {
console.log("Bye!");
};
Read the error carefully, because it is telling you something precise. It does not say sayBye is not defined, because the name exists. It says sayBye is not a function, because at that moment sayBye holds undefined, and calling undefined is a type error. The function only reaches the variable when execution gets to the assignment.
Arrow functions follow the same rule, for the same reason:
calculate(); // TypeError: calculate is not a function
var calculate = () => 2 + 2;
Nothing about the arrow syntax changes anything. What matters is that the name was introduced by var, so the memory phase gave it undefined and left it there.
The practical consequence is worth stating plainly: moving a function declaration around a file is safe, and moving a function expression is not. If you extract a helper into a const at the bottom of a module and something above it calls it during initialisation, you will get a TypeError that looks nothing like the change you made.
init(); // TypeError: init is not a function
const init = () => {
console.log("ready");
};
Note that this one is a const, not a var, so the error arrives for a slightly different reason: const sits in its Temporal Dead Zone rather than holding undefined. Either way the call fails, and either way moving the declaration above the call fixes it. The rule to carry forward is that only a function declaration is safe to call from above.
EXERCISE
3The Hoisting Cheat Sheet
Every interview question about hoisting boils down to one question: what did Phase 1 put in memory? Here is your complete reference.
Every hoisting question reduces to a single question you can ask yourself: what did the memory phase put in this slot before anything ran? There are only a few possible answers, and once you can recite them the puzzles stop being puzzles.
Predict the output of this before reading on. All five lines run before their declarations:
console.log(a);
console.log(b);
console.log(c);
d();
e();
var a = 10;
let b = 20;
const c = 30;
function d() {
console.log("I am d");
}
var e = function () {
console.log("I am e");
};
Work through it slot by slot. a is a var, so it holds undefined and printing it is fine. b and c are let and const: they exist, but reading them before their declaration line throws, so line two ends the program. d is a function declaration, stored complete, so it would print. e is a var holding undefined, so calling it would be a TypeError.
In practice the program stops at console.log(b), because the first error ends execution. Comment out that line and it stops at c. Comment out both and d() prints while e() throws.
The same program, with the declarations moved above their uses:
var a = 10;
let b = 20;
const c = 30;
function d() {
console.log("I am d");
}
var e = function () {
console.log("I am e");
};
console.log(a); // 10
console.log(b); // 20
console.log(c); // 30
d(); // "I am d"
e(); // "I am e"
Every line now behaves the way it reads. That is the practical lesson underneath the trivia: hoisting is not a feature to exploit, it is a behaviour to understand so that you can write code where it never comes up.
The full set of rules, which is shorter than it looks:
| Declared as | Slot exists before execution | What is in it |
|---|---|---|
var | yes | undefined |
let | yes | unreadable until its line runs |
const | yes | unreadable until its line runs |
| function declaration | yes | the complete function |
function in a var | yes | undefined |
| never declared | no | ReferenceError on read |
Three distinct failures live in that table and they are easy to confuse. undefined means the slot is there and empty. TypeError: x is not a function means the slot is there, empty, and you tried to call it. ReferenceError means either there is no slot at all, or there is one you are not yet allowed to touch.
Pro Tip: That last case, a slot you are not allowed to touch, is
letandconstbefore their declaration line, and it has a name: the Temporal Dead Zone. The next lesson is about why it exists and why it is an improvement rather than an inconvenience.
