Scope and the Scope Chain
Scope is the region of a program where a variable can be used. A variable declared inside a function exists only in that function; one declared inside a { } block with let or const exists only in that block. When code uses a name, JavaScript looks for it in the current scope, then in the scope around it, and so on outward: that path is the scope chain. Scope is what lets two functions both use a variable called total without interfering, and it is the foundation of closures.
In One Minute
- Block scope:
let,constandclassdeclared inside{ }exist only in that block. - Function scope: parameters and variables declared in a function (including
var) exist only in that function. - Module scope: top-level declarations in an ES module are private to that file. Global scope is shared by all classic scripts on a page.
- Name lookup walks outward through enclosing scopes until it finds the name, or throws
ReferenceError. - Scope is lexical: it is decided by where code is written, not where it is called from.
Kinds of Scope
| Scope | Created by | Holds |
|---|---|---|
| Global | The top level of a classic <script> | Variables visible to all scripts on the page |
| Module | Each ES module file | Top-level declarations of that file only |
| Function | Every function call | Parameters, var, let, const, inner functions |
| Block | Any { }: if, for, while, a bare block | let, const, class declared inside |
Block Scope
const fee = 450;
if (fee > 100) {
const discount = 45;
let message = `Discount: $${discount}`;
console.log(message);
}
console.log(typeof discount, typeof message);
for (let i = 0; i < 2; i++) {
const line = `Round ${i}`;
console.log(line);
}
console.log(typeof i, typeof line);Discount: $45
undefined undefined
Round 0
Round 1
undefined undefinedExplanation: discount, message, i and line exist only inside their blocks. After the block ends, the names are gone; typeof reports "undefined" for a name that doesn't exist (instead of throwing). Keeping variables in the smallest block that needs them means less to keep track of.
Function Scope
function lateFee(daysLate) {
const rate = 2;
var cap = 30;
return Math.min(daysLate * rate, cap);
}
console.log(lateFee(20));
console.log(typeof rate, typeof cap, typeof daysLate);30
undefined undefined undefinedEach call to lateFee gets fresh daysLate, rate and cap variables, which disappear when it returns (unless a closure keeps them, as a later lesson shows). var ignores blocks but respects functions: it is function-scoped.
Global and Module Scope
In a classic script (a <script> without type="module"), top-level variables are global: every script on the page shares them. Top-level var declarations and function declarations even become properties of the global object (window in browsers):
// In a classic <script> on a page:
var appName = "Fee Tracker";
let version = 3;
console.log(window.appName); // "Fee Tracker": var creates a window property
console.log(window.version); // undefined: let doesn't, but it is still globalIn an ES module (<script type="module"> or a Node.js .mjs file), top-level declarations stay in the module. Other files can only use what the module exports. This is one of the biggest reasons modern code uses modules: no accidental collisions between files.
The Scope Chain
Scopes are nested: a block sits inside a function, which may sit inside another function, which sits inside the module. When code uses a name, JavaScript searches:
- the current scope,
- then the scope that encloses it,
- and so on outward to the module or global scope.
It uses the first match it finds. If no scope has the name, reading it throws a ReferenceError.
const currency = "USD";
function makeReport(owner) {
const header = `Report for ${owner}`;
function line(amount) {
return `${header}: ${amount} ${currency}`;
}
return line(120);
}
console.log(makeReport("Navika"));
try {
console.log(header);
} catch (err) {
console.log(err.name + ": " + err.message);
}Report for Navika: 120 USD
ReferenceError: header is not definedExplanation: inside line, the name amount is found in line's own scope, header one level out in makeReport, and currency two levels out at the top. The search only goes outward: the top-level code can't see header, because it is inside makeReport.
Shadowing
When an inner scope declares a name that also exists outside, the inner one shadows (hides) the outer one within that scope:
const total = 1000;
function studentTotal(fees) {
const total = fees.reduce((sum, f) => sum + f, 0);
return total;
}
console.log(studentTotal([120, 85]));
console.log(total);205
1000Inside studentTotal, total refers to the local variable; the outer total is untouched. Shadowing is legal and sometimes useful, but it can confuse readers who expect the outer variable. Linters can warn about it (no-shadow).
Lexical Scope
JavaScript uses lexical scope (also called static scope): what a function can see is decided by where it is written, not by where it is called from:
const label = "outer";
function show() {
return label;
}
function caller() {
const label = "caller";
return show();
}
console.log(caller());outerExplanation: show was written at the top level, so it looks up label there and finds "outer". The fact that caller has its own label doesn't matter, because show isn't written inside caller. You can tell what any function can access just by reading the code around it.
In Practice
The Fee Tracker keeps configuration at module level, data processing in functions, and temporary values in the smallest block:
const GRACE_DAYS = 10;
const RATE = 2;
function lateFees(students) {
const results = [];
for (const student of students) {
const extraDays = student.daysLate - GRACE_DAYS;
if (extraDays <= 0) continue;
const fee = extraDays * RATE;
results.push(`${student.name}: $${fee}`);
}
return results;
}
console.log(lateFees([
{ name: "Navika", daysLate: 3 },
{ name: "Srihitha", daysLate: 16 },
{ name: "Advitha", daysLate: 25 },
]));['Srihitha: $12', 'Advitha: $30']extraDays and fee live only inside one loop round, so they can never leak into the next student's calculation.
Common Mistakes
Using a block variable after the block. ReferenceError. Declare it in the outer scope if you need it there.
Assigning to an undeclared name. In sloppy mode, total = 5 without let creates a global. In strict mode and modules, it throws ReferenceError. Always declare.
Accidental shadowing. A parameter named like an outer variable hides it. Use distinct names when the outer one is needed.
Expecting dynamic scope. A function doesn't see the caller's local variables. Pass them as arguments.
Under the Hood
The specification models each scope as an environment record: a table of the names declared in that scope, plus a link to the outer environment. Every time a function is called, a new environment is created whose outer link is the environment where the function was defined (stored in the function's internal [[Environment]] slot when the function was created). Blocks with let or const get their own small environment too, and a for (let ...) loop gets a fresh one per round.
The scope chain is simply this linked list of environments. Name lookup follows the links outward. Because the outer link comes from where the function was created, not where it was called, scope is lexical. And because a function keeps a reference to its defining environment, that environment stays alive as long as the function does, which is exactly what a closure is. Engines like V8 analyze scopes when parsing, so they know at compile time which variables are captured by inner functions and only allocate those on the heap; everything else stays in fast registers or stack slots.
Interview Corner
What is the scope chain?
The sequence of nested lexical environments used to resolve identifiers. Lookup starts in the current environment and follows each environment's outer reference until the name is found or the global environment is exhausted, which throws a ReferenceError. The chain is fixed by where functions are defined (lexical scoping).
What is the difference between block scope and function scope?
let, const and class are scoped to the nearest enclosing block. var and function parameters are scoped to the enclosing function, ignoring blocks. That's why a var declared in an if is visible after it, while a let isn't.
What is lexical scope?
Scope determined by the physical structure of the source code. A function resolves free variables in the scopes surrounding its definition, regardless of where it is invoked. Closures depend on it.
Practice
Challenge: Predict what each console.log prints, then run it. Then rename one variable so the second line prints outer without changing the first line's output.
const value = "outer";
function test() {
const value = "inner";
console.log(value);
return () => value;
}
console.log(test()());Show solution
const value = "outer";
function test() {
const localValue = "inner";
console.log(localValue);
return () => value;
}
console.log(test()());inner
outerKey Takeaways
| Declared with | Scope |
|---|---|
let, const, class | Nearest block |
var | Nearest function |
| Function parameter | The function |
| Top level of a module | The module |
| Top level of a classic script | Global |
Was this tutorial helpful?