Hoisting
Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution. Function declarations are fully hoisted, var is partially hoisted (undefined), and let/const have a 'temporal dead zone'.
Hoisting Rules
- Function declarations — Fully hoisted. Can call before definition: greet() works before function greet() { }
- var — Declaration hoisted, value is NOT. Variable exists but is undefined until the assignment line
- let/const — NOT hoisted (technically hoisted but in 'temporal dead zone'). ReferenceError if accessed before declaration
- Function expressions — NOT hoisted (they use let/const). const greet = function() { } must be defined first
- Best practice — Always declare variables at the top of their scope. Don't rely on hoisting
Hoisting Code
// Function declarations are hoisted ✅
sayHello(); // Works! "Hello, World!"
function sayHello() {
console.log("Hello, World!");
}
// var is partially hoisted (undefined)
console.log(x); // undefined (not ReferenceError!)
var x = 10;
console.log(x); // 10
// What JS actually does with var:
// var x; ← declaration hoisted
// console.log(x); ← undefined
// x = 10; ← assignment stays here
// console.log(x); ← 10
// let/const — temporal dead zone ❌
// console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 20;
console.log(y); // 20
// Function expressions are NOT hoisted
// greet(); // ❌ TypeError: greet is not a function
const greet = function() {
console.log("Hi!");
};
greet(); // ✅ Works after definition
// Best practice: always declare first
const name = "Alice"; // declare at top
const age = 25;
function introduce() { // declarations can go anywhere (hoisted)
console.log(`${name}, ${age}`);
}
introduce();Tip
Tip
Don't rely on hoisting — always declare variables and functions at the top of their scope. Code that depends on hoisting is confusing and error-prone. Write code that reads top-to-bottom naturally.
Function + environment.
Common Mistake
Warning
Expecting let/const to hoist like var. With var, accessing before declaration gives undefined. With let/const, it throws ReferenceError (temporal dead zone). This difference catches many developers switching from var to let.
Practice Task
Note
Test hoisting: (1) Call a function declaration before its definition — it works. (2) Try calling a function expression before its definition — observe the error. (3) Log a var variable before its declaration (shows undefined) vs a let variable (ReferenceError).
Quick Quiz
Key Takeaways
- Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution.
- Function declarations — Fully hoisted. Can call before definition: greet() works before function greet() { }
- var — Declaration hoisted, value is NOT. Variable exists but is undefined until the assignment line
- let/const — NOT hoisted (technically hoisted but in 'temporal dead zone'). ReferenceError if accessed before declaration