Scope
What it means
Section titled βWhat it meansβ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).
Examples
Section titled βExamplesβ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 boundariesconsole.log(blockScoped); // ReferenceError -- let respects the blockCommon mistake
Section titled βCommon mistakeβ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 loopQuick practice
Section titled βQuick practiceβ-
Whatβs the key difference between
varandletin terms of scope?Answer
varis function-scoped (ignores block boundaries likeifandfor);let/constare block-scoped, confined to the nearest enclosing{}. -
Can an inner function access variables declared in its outer (enclosing) function?
Answer
Yes β this is lexical scoping. The reverse isn't true: an outer function cannot access variables declared inside an inner function. -
After a
for (var i = ...)loop finishes, isistill accessible outside the loop?Answer
Yes β becausevaris function-scoped, not block-scoped,i"leaks" into the enclosing function or global scope.