After this lesson you will understand why some code works even though a name is used before its definition, why other code breaks, and how to avoid depending on the difference.
What hoisting is
JavaScript does not run your code line by line from the very first moment. Before a scope runs, the engine reads through it and registers the declarations in that scope. As a result, certain names exist before the line that declares them is reached.
People describe this as declarations being "moved to the top". That is a handy picture but not literally true. Nothing is rewritten; the names are simply set up first. What differs is what each kind of declaration holds at that early moment.
Function declarations
A function declaration is hoisted completely, name and body. You can call it anywhere in its scope:
console.log(add(2, 3)); // 5
function add(a, b) {
return a + b;
}Many developers use this on purpose: they put the main flow at the top of a file and the helper functions below.
var variables
A var declaration is hoisted too, but only the declaration, not the value. Until the assignment line runs, the variable is undefined:
console.log(score); // undefined
var score = 10;
console.log(score); // 10JavaScript treats the code as if it were:
var score;
console.log(score);
score = 10;
console.log(score);This is a major reason var is discouraged. A typo or reordering gives you undefined rather than an error, and the bug appears far away.
let and const: the temporal dead zone
let and const are also registered early, but they cannot be used until their declaration line runs. The span between the start of the scope and that line is the temporal dead zone. Touching the name there throws a ReferenceError:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
function show(text) {
out.textContent += text + "\n";
}
try {
show(String(price));
let price = 20;
} catch (error) {
show(error.name + ": " + error.message);
}
</script>The error is a good thing. Reading a value before it exists is almost always a mistake, and the message tells you straight away. The exact wording of the message varies between browsers, but the name is ReferenceError.
Function expressions and arrows are not hoisted as functions
A function stored in a variable follows the variable's rules, not the declaration rules:
try {
sayHi();
} catch (error) {
console.log(error.name); // TypeError
}
var sayHi = function () {
return "hi";
};Because var sayHi starts as undefined, the call tries to run undefined, giving TypeError. With let or const, you would get a ReferenceError instead. In both cases the function is not usable yet.
A quick reference:
| Written as | Usable before its line? | If you try |
|---|---|---|
function f() {} |
Yes | Works |
var x = ... |
Name exists, value is undefined |
undefined |
let x / const x |
No | ReferenceError |
const f = () => {} |
No | ReferenceError |
var f = function () {} |
Name exists, not callable | TypeError |
Hoisting and scope
Hoisting happens per scope. A var inside a function is hoisted to the top of that function. A let inside a block is registered at the top of that block.
A subtle consequence: a let in an inner block hides the outer variable of the same name for the whole block, including the part before the declaration. That is why an early read throws instead of quietly reading the outer value.
const label = "outer";
function show() {
try {
console.log(label);
} catch (error) {
console.log(error.name); // ReferenceError
}
const label = "inner";
}
show();How to live with hoisting
You do not need to memorise every detail. A few habits make hoisting a non-issue:
- Use
constby default andletwhen a value changes. Avoidvar. - Declare variables at the top of the scope where they are used, before using them.
- Use function declarations for helpers you want to call from anywhere in the file, or define functions before the code that calls them.
- Treat any "used before defined" message as a sign that code is in the wrong order.
See Scope for where variables live and Variables for the basics of let, const and var.
Common mistakes
Believing the value is hoisted. Only var's declaration moves; the assignment stays where you wrote it.
Calling a function expression too early. A function in a const is not available until its line has run.
Reading outer variables by accident. Declaring a let with the same name as an outer one makes the earlier lines throw.
Using var in loops and conditions. It leaks out of the block and is hoisted, which hides bugs.
Reordering code during refactoring and breaking something that worked only because of hoisting.
Exercise
Without running it, predict what each of these prints or throws, then check in the editor: (1) call a function declaration before it is defined; (2) log a var before assignment; (3) log a const before assignment, inside try/catch; (4) call a const arrow function before its line, inside try/catch. Write one sentence for each explaining why.
Next: Closures.
Key points
- Before running code, JavaScript registers declarations in each scope, which is why they seem to move to the top.
- Function declarations are fully hoisted, so you can call them before the line that defines them.
- var variables are hoisted and start as undefined; let and const are hoisted but cannot be used before their line.
- Using a let or const name too early throws a ReferenceError, from the temporal dead zone.
- The safe habit is to declare everything before you use it.