Interview question
What is scope and the scope chain in JavaScript? JavaScript में scope और scope chain क्या है?
Answer
Scope determines the accessibility of variables. JavaScript has global scope, function scope, and block scope (with let/const).
// Global scope
let global = 'I am global';
function outer() {
let outerVar = 'outer';
function inner() {
let innerVar = 'inner';
console.log(innerVar); // 'inner' - own scope
console.log(outerVar); // 'outer' - parent scope
console.log(global); // 'I am global' - global scope
}
inner();
}
outer();| Scope Type | Description |
|---|---|
| Global scope | Variables accessible everywhere |
| Function scope | Variables accessible only within the function |
| Block scope | Variables (let/const) accessible only within the block (if, for, etc.) |
| Scope chain | JavaScript looks up variable in local scope, then parent scopes, then global |
Interview tip: Scope chain means inner functions can access variables from outer functions, but outer functions cannot access inner function variables.
Scope यह तय करता है कि variables कहाँ accessible हैं। JavaScript में global scope, function scope, और block scope (let/const के साथ) होता है।
let global = 'I am global';
function outer() {
let outerVar = 'outer';
function inner() {
let innerVar = 'inner';
console.log(innerVar); // 'inner'
console.log(outerVar); // 'outer'
console.log(global); // 'I am global'
}
inner();
}
outer();| Scope Type | Description |
|---|---|
| Global scope | Variables everywhere accessible |
| Function scope | सिर्फ function के अंदर accessible |
| Block scope | सिर्फ block (if, for) के अंदर (let/const) |
| Scope chain | JavaScript local से फिर parent scopes से फिर global से खोजता है |
इंटरव्यू टिप: Scope chain का मतलब inner functions outer function के variables access कर सकते हैं, पर उल्टा नहीं।
Was this answer clear?