📈 Hoisting = Declarations Move to Top
JavaScript hoists declarations. Understand hoisting to avoid bugs. var, let, const, function declarations — different hoisting behavior.
📝 var Hoisting
console.log(x); // undefined (not error)
var x = 5;
// Equivalent to:
var x;
console.log(x); // undefined
x = 5;
// Function declaration hoisting
sayHello(); // Works!
function sayHello() {
console.log('Hello');
}
// Function expression hoisting (only declaration, not value)
sayHi(); // TypeError: sayHi is not a function
var sayHi = function() {
console.log('Hi');
};
🎯 let and const Hoisting (Temporal Dead Zone)
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5;
// TDZ (Temporal Dead Zone)
// let and const are hoisted but not initialized
// Access before declaration = error
// const hoisting
console.log(y); // ReferenceError
const y = 10;
// Function declaration with block scope
if (true) {
function test() { console.log('test'); }
}
test(); // Works (function declarations hoisted to top of scope)
// Arrow functions (not hoisted)
arrow(); // ReferenceError: arrow is not defined
const arrow = () => console.log('arrow');
💡 Summary
- var: Hoisted, initialized undefined
- let/const: Hoisted, but TDZ (cannot access before declaration)
- Function declarations: Fully hoisted (can call before declaration)
- Function expressions: Only variable hoisted
- Use let/const to avoid hoisting surprises
“Hoisting surprised me. var returns undefined, let returns ReferenceError. Understanding hoisting prevents bugs. Essential JavaScript knowledge.”
