What is hoisting in JavaScript and how does it work? JavaScript में hoisting क्या है और यह कैसे काम करता है?
Hoisting is JavaScript's behavior of moving declarations to the top of their scope before code execution.
// Variable hoisting
console.log(x); // undefined (not ReferenceError)
var x = 5;
// Function hoisting
greet(); // 'Hello' - works because function is hoisted
function greet() { console.log('Hello'); }
// let/const hoisting (Temporal Dead Zone)
console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;| Type | Hoisted? | Initialized to? | Accessible before declaration? |
|---|---|---|---|
| var declaration | Yes | undefined | Yes (gives undefined) |
| let/const declaration | Yes (in TDZ) | Not initialized | No (ReferenceError) |
| Function declaration | Yes | Function body | Yes |
| Function expression | No | N/A | No |
Interview tip: Explain that hoisting happens at compile-time, not runtime. All declarations (var, let, const, function) are hoisted, but var is initialized to undefined while let/const enter a Temporal Dead Zone.
Hoisting JavaScript का एक behavior है जहाँ declarations को उनके scope के top पर move किया जाता है code execution से पहले।
console.log(x); // undefined (ReferenceError नहीं)
var x = 5;
greet(); // 'Hello' - काम करता है क्योंकि hoisted है
function greet() { console.log('Hello'); }
console.log(y); // ReferenceError
let y = 10;| Type | Hoisted? | Initialized to? | Declaration से पहले accessible? |
|---|---|---|---|
| var | हाँ | undefined | हाँ (undefined देता है) |
| let/const | हाँ (TDZ में) | नहीं | नहीं (ReferenceError) |
| Function declaration | हाँ | Function body | हाँ |
| Function expression | नहीं | N/A | नहीं |
इंटरव्यू टिप: समझाएं hoisting compile-time पर होता है। सभी declarations hoisted होते हैं, पर var को undefined में initialize किया जाता है जबकि let/const को TDZ में रखा जाता है।
Was this answer clear?