Hoisting
JavaScript reads your whole file before running it, which is why a function declaration works above the line that defines it.
Declarations are registered before any code runs. Function declarations are fully available early; var names exist as undefined; let and const exist but cannot be touched until their line, which is the Temporal Dead Zone.
EXERCISE
1JavaScript Reads Before It Runs
Before a single line executes, the engine scans the code and registers every declaration it can find.
This explains the behaviour you saw in the last two lessons: a function works before it is written, a const does not.
Function declarations are available immediately:
console.log(double(4)); // 8 <- called before it appears
function double(n) {
return n * 2;
}
// The whole function was registered before line 1 ran.
var names exist early, but hold undefined:
console.log(count); // undefined <- not a ReferenceError
var count = 5;
console.log(count); // 5
// What the engine effectively did:
// var count; <- registered, set to undefined
// console.log(count); <- undefined
// count = 5; <- the assignment happens here, in order
let and const throw instead:
console.log(total); // ReferenceError: Cannot access 'total' before initialization
const total = 10;
// Note the wording. It is NOT "total is not defined".
// The engine knows total exists. It is refusing to let you touch it yet.
A genuinely undeclared name says something different:
console.log(nothing); // ReferenceError: nothing is not defined
// Two different messages, two different problems:
// "Cannot access X before initialization" -> declared below, wait for it
// "X is not defined" -> never declared, check spelling
Pro Tip: Read the error message carefully, because the two
ReferenceErrorwordings point at completely different bugs. "Cannot access before initialization" means you used something too early. "Is not defined" means it does not exist at all, which is nearly always a typo or a missing import.
EXERCISE
2The Temporal Dead Zone
Between the top of a block and the line that declares a let or const, the name exists but using it throws, and that gap has a name.
The Temporal Dead Zone is the stretch of code where a let or const has been registered but not yet initialised.
Seeing the zone:
{
// TDZ for `message` starts here
// console.log(message); would throw
// console.log(message); still throws
const message = "Hello"; // TDZ ends on this line
console.log(message); // Hello
}
Why it exists, instead of just giving undefined like var:
// With var, a typo produces a confusing value:
function withVar() {
console.log(userName); // undefined, and the code carries on
var userName = "Ada";
// Somewhere far below, something breaks because of that undefined.
}
// With const, it stops at the actual mistake:
function withConst() {
console.log(userName); // ReferenceError, right here
const userName = "Ada";
}
It catches a real shadowing bug:
const role = "admin";
function check() {
console.log(role); // ReferenceError, not "admin"
const role = "editor"; // this declaration shadows the outer one
}
check();
// The inner `role` shadows the outer one for the WHOLE function,
// including the lines above its declaration. The TDZ makes that
// visible instead of silently reading the outer value.
Pro Tip: The Temporal Dead Zone sounds like an obstacle and is actually a safety net. It turns "your variable silently held undefined for a while" into "you used this too early, on this exact line". Every error it produces is a bug it found, and the fix is always the same: move the declaration above the use.
EXERCISE
3Writing Code That Does Not Depend on Hoisting
Hoisting is worth understanding so you can read other people's code and your own error messages, not so you can rely on it.
The style that works regardless:
// Declare before you use. Every time.
const taxRate = 0.18;
function addTax(amount) {
return amount * (1 + taxRate);
}
console.log(addTax(100)); // 118
Function declarations hoist, so this common shape is fine:
// Main logic at the top, helpers below: readable, and it works.
start();
function start() {
console.log(formatName("ada lovelace"));
}
function formatName(name) {
return name
.split(" ")
.map((part) => part[0].toUpperCase() + part.slice(1))
.join(" ");
}
// Ada Lovelace
That split, map and join chain is Unit 6 and Unit 7 material. It is here only to show a helper defined below the code that calls it.
The same shape with arrows does not work:
// start(); // ReferenceError
const start2 = () => {
console.log("running");
};
start2(); // fine, now that the line has run
Two habits that make hoisting a non-issue:
// 1. const and let for values, always, never var.
// You then get an error instead of a silent undefined.
// 2. Top-level function declarations for named helpers,
// arrows for the small ones you pass to other functions.
// Both are then defined before anything calls them.
You do not need to write code that exploits hoisting, and you should not try to. What you need is to recognise it when you read a file that calls a function defined two hundred lines below, and to understand the error message when something is used too early. Declare before use and the whole topic becomes trivia you can explain in an interview.
