Interview question
What are the differences between var, let, and const in JavaScript? JavaScript में var, let और const में क्या अंतर है?
Answer
| Keyword | Scope | Hoisting | Re-declaration | Re-assignment |
|---|---|---|---|---|
| var | Function-scoped | Hoisted, initialized as undefined | Yes | Yes |
| let | Block-scoped | Hoisted but not initialized (TDZ) | No | Yes |
| const | Block-scoped | Hoisted but not initialized (TDZ) | No | No |
function test() {
console.log(x); // undefined (hoisting)
var x = 1;
if (true) {
let y = 2; // block-scoped
const z = 3; // block-scoped, can't be reassigned
}
console.log(y); // ReferenceError: y is not defined
}Interview tip: Always use const by default, let if reassignment needed, and avoid var. Mention Temporal Dead Zone (TDZ) for let/const.
| Keyword | Scope | Hoisting | Re-declaration | Re-assignment |
|---|---|---|---|---|
| var | Function-scoped | Hoisted, undefined | हाँ | हाँ |
| let | Block-scoped | Hoisted नहीं (TDZ) | नहीं | हाँ |
| const | Block-scoped | Hoisted नहीं (TDZ) | नहीं | नहीं |
function test() {
console.log(x); // undefined (hoisting)
var x = 1;
if (true) {
let y = 2; // block-scoped
const z = 3; // block-scoped
}
console.log(y); // ReferenceError
}इंटरव्यू टिप: Default const use करें, reassignment चाहिए तो let, var से बचें। Temporal Dead Zone (TDZ) का ज़िक्र करें।
Was this answer clear?