Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope (either global or function scope) during the compilation phase, before code execution.
🔹 Key Points:
- Only declarations are hoisted, not initializations.
- Function declarations are hoisted with their definitions.
vardeclarations are hoisted but initialized asundefined.letandconstare also hoisted, but remain in the Temporal Dead Zone (TDZ) until initialized, so accessing them before declaration causes a ReferenceError.
✅ Example with var:
console.log(a); // undefined
var a = 10;
Internally behaves like:
var a;
console.log(a);
a = 10;
✅ Example with let or const:
console.log(b); // ❌ ReferenceError
let b = 20;
✅ Function Hoisting:
greet(); // ✅ Works
function greet() {
console.log("Hello!");
}
📝 In Summary:
Hoisting allows you to use variables and functions before they are declared in the code, but understanding how different declarations (var, let, const, functions) behave is crucial to avoid bugs.