30 Mins upper-intermediate
15. Hoisting
Core Mechanics
Hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope before code execution. This can cause bizarre bugs if you don't understand how it works.
๐๏ธ Function Hoisting
Function declarations are completely hoisted. This means you can call a function before you actually write its definition in the code.
// Calling it before it exists!
greet();
function greet() {
console.log("Hello from the hoisted function!");
}
OutputHello from the hoisted function!
๐ฆ Variable Hoisting (var vs let/const)
Variables declared with the old var keyword are hoisted, but their values are not. They are initialized as undefined.
Variables declared with let and const are hoisted, but they enter a "Temporal Dead Zone" and cannot be accessed before initialization.
// Using var:
console.log(legacyVar); // Outputs: undefined (does not crash)
var legacyVar = "I am var";
// Using let:
try {
console.log(modernVar);
} catch (e) {
console.error("Crash!", e.message);
}
let modernVar = "I am let";
Outputundefined
Crash! Cannot access 'modernVar' before initialization
Crash! Cannot access 'modernVar' before initialization
Knowledge Check
Ready to test your understanding of 15. Hoisting?