Hoisting is JavaScript’s behavior of moving declarations to the top of their scope during the compile phase. This doesn’t mean code is physically moved—JavaScript just knows about certain variables and functions before execution starts.
varundefinedundefined)console.log(a); // undefinedvar a = 10;
⚠️ This can cause subtle bugs because accessing a before assignment doesn’t throw an error.
letconsole.log(b); // ❌ ReferenceErrorlet b = 10;
constletconsole.log(c); // ❌ ReferenceErrorconst c = 10;
✅ let and const are safer than var because they prevent early access.
sayHello();function sayHello() {console.log("Hello!");}
✔️ This works because the entire function is hoisted.
varsayHi(); // ❌ TypeError: sayHi is not a functionvar sayHi = function () {console.log("Hi");};
undefinedlet / constsayHey(); // ❌ ReferenceErrorconst sayHey = function () {console.log("Hey");};
| Declaration | Hoisted | Initialized | Scope | Safe to Access Early |
|---|---|---|---|---|
var | ✅ | undefined | Function | ⚠️ Yes (but risky) |
let | ✅ | ❌ | Block | ❌ |
const | ✅ | ❌ | Block | ❌ |
| Function Declaration | ✅ | ✅ | Function | ✅ |
| Function Expression | Partial | ❌ | Depends | ❌ |