Skip to content

Scope

Scope determines where a variable is visible and accessible in your code. JavaScript has three levels: global scope (accessible everywhere), function scope (var is confined to the nearest enclosing function), and block scope (let/const are confined to the nearest enclosing {}, including if blocks and loops).

let globalVar = "I'm global";
function outer() {
let outerVar = "I'm in outer";
function inner() {
let innerVar = "I'm in inner";
console.log(globalVar); // accessible -- global scope
console.log(outerVar); // accessible -- inner can see outer's scope
console.log(innerVar); // accessible -- its own scope
}
inner();
console.log(innerVar); // ReferenceError -- outer can't see inner's scope
}
if (true) {
let blockScoped = "only visible in this block";
var functionScoped = "visible in the whole function/global scope";
}
console.log(functionScoped); // works -- var ignores block boundaries
console.log(blockScoped); // ReferenceError -- let respects the block

Assuming var respects block scope like let/const β€” declaring var inside an if or for block actually attaches it to the surrounding function (or global scope), which can leak variables further than intended.

for (var i = 0; i < 3; i++) {
// loop body
}
console.log(i); // 3 -- `i` leaked out of the loop entirely, since var is function-scoped
for (let j = 0; j < 3; j++) {
// loop body
}
console.log(j); // ReferenceError -- `j` is properly confined to the loop
  1. What’s the key difference between var and let in terms of scope?

    Answervar is function-scoped (ignores block boundaries like if and for); let/const are block-scoped, confined to the nearest enclosing {}.
  2. Can an inner function access variables declared in its outer (enclosing) function?

    AnswerYes β€” this is lexical scoping. The reverse isn't true: an outer function cannot access variables declared inside an inner function.
  3. After a for (var i = ...) loop finishes, is i still accessible outside the loop?

    AnswerYes β€” because var is function-scoped, not block-scoped, i "leaks" into the enclosing function or global scope.