Sub topic 1
What Scope Means in JavaScript
Every time JavaScript runs console.log(total), it has to work out which total you mean. Several variables with that name can exist at once, and some may not be reachable from the current line at all. The rules for answering that question are called scope. This chapter builds the working model the rest of the tutorial uses. Later chapters add detail to it, covering global, function, block, and module scope, the scope chain, hoisting, and closures.
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic JavaScript syntax.
- Declare variables with
var,let, andconst. - Write functions and call them.
- Use
ifstatements andforloops. - Run code in a browser console or with Node.js (
node file.js).
You don't need to know how var and let differ in visibility. That comes in the next few chapters.
Scope, Bindings, and Identifiers
Some vocabulary makes the rest of the tutorial precise:
| Term | Meaning | Example |
|---|---|---|
| Identifier | A name written in source code | `total` in `total + 1` |
| Binding | The link between a name and a storage slot holding a value | `let total = 0` creates a binding for `total` |
| Scope | The region of code where a binding can be reached by its name | The body of the function that declared `total` |
| Environment | The runtime structure that holds the bindings of one scope | Created each time a function is called |
Scope is a property of code regions. An environment is the runtime object that exists while that region runs. The ECMAScript specification calls environments "Environment Records". You will see "lexical environment" in many articles, and it means roughly the same thing.
A binding belongs to exactly one scope. When code uses an identifier, JavaScript looks for a matching binding, starting in the current scope and moving outward. If it finds none, reading the name throws a ReferenceError.
function makeSecret() {
const secret = 42;
return secret * 2;
}
console.log(makeSecret()); // 84
try {
console.log(secret);
} catch (e) {
console.log(e.name); // "ReferenceError"
}The binding secret lives in the scope of makeSecret. Code outside that function has no path to it, so the lookup fails.
Lexical Scope: Decided by Where Code Is Written
JavaScript uses lexical scope, also called static scope. "Lexical" refers to the text of the program. What a function can see depends on where the function is written in the source. Where it is called doesn't matter.
const name = "top-level";
function show() {
return name;
}
function caller() {
const name = "caller";
return show();
}
console.log(caller()); // "top-level"show is called from inside caller, and caller has its own name. Even so, show returns "top-level". The reason is that show was written at the top level, so its outer scope is the top level, and that is where it finds name. The local name inside caller is invisible to show.
A language with dynamic scope would follow the call stack instead and return "caller". Some shell languages and older Lisps work that way. JavaScript does not.
Why lexical scope helps you
Scope is fixed by the source text, so you can work out what any identifier refers to by reading the code. You don't have to trace every possible caller. Editors, linters, and bundlers rely on the same fact. They can rename variables safely and flag undefined names before the code ever runs.
Scopes Nest
Scopes sit inside one another the way the code does. Each function body creates a scope. Each { ... } block creates one for let, const, and class declarations. A file is a scope too, and so is the global environment around everything. An inner scope can see the bindings of every scope that encloses it. An outer scope cannot see inward.
const a = "A";
function outer() {
const b = "B";
function inner() {
const c = "C";
return [a, b, c].join("");
}
console.log(typeof c); // "undefined" (c is not visible here)
return inner();
}
console.log(outer()); // "ABC"inner reaches a, b, and c. outer reaches a and b but not c. The typeof check avoids an error because typeof on an unresolvable name returns "undefined" instead of throwing. A later chapter shows the one case where typeof does throw.
The kinds of scope you will meet in this tutorial:
| Scope kind | Created by | Holds | Covered in |
|---|---|---|---|
| Global | The runtime (browser window, Node process) | Top-level script declarations, built-ins | The Global Scope |
| Module | Each ES module file | Top-level declarations in that module | Module Scope in ES Modules |
| Function | Each function call | Parameters, `var`, `let`, `const`, inner functions | Function Scope |
| Block | `{ }`, `if`, `for`, `switch`, `try`/`catch` | `let`, `const`, `class` (not `var`) | Block Scope with let and const |
The structure of the code determines which scopes exist. A new environment is created each time that code runs, though. Two calls to the same function get two separate sets of bindings. The closures chapter depends on this fact.
function tally(n) {
const doubled = n * 2;
return doubled;
}
console.log(tally(1)); // 2
console.log(tally(5)); // 10 (a fresh doubled binding for this call)Scope Is Not `this`
A common source of confusion is mixing scope up with this. Scope is lexical. For ordinary functions, this is set by how the function is called. The two follow different rules.
const label = "lexical";
function report() {
return [label, this && this.label];
}
const obj = { label: "object", report };
console.log(obj.report()); // ["lexical", "object"]The plain identifier label resolves through scope to the top-level "lexical". The expression this.label reads a property of whatever object this points to. Here that is obj, because the call was written obj.report(). Property lookup on an object is a separate mechanism from variable lookup. An object's properties never become variables in scope, even inside its methods.
Exceptions to Static Scope
Two old features can change scope at runtime, and both are discouraged:
withstatements put an object's properties into scope dynamically. They are a syntax error in strict mode and in ES modules.- Direct
evalin sloppy mode can add newvarbindings to the surrounding function scope. In strict mode,evalgets its own scope and cannot add bindings to the caller.
Modern code avoids both. Once you set them aside, the rule holds: you can read a program's scopes from its source.
Common Errors This Model Explains
| Symptom | Usual cause |
|---|---|
| `ReferenceError: x is not defined` | No binding named `x` in any enclosing scope |
| A function reads an "old" or unexpected value | It resolves the name lexically, not from its caller |
| Changing a variable in one function doesn't affect another | Each has its own binding with the same name |
| A helper can't see a caller's local variable | Callers' locals are never in the callee's scope; pass them as arguments |
The last row shows a design habit. When a function needs data from its caller, pass it as a parameter instead of hoping scope will provide it.
function formatPrice(amount, currency) {
return `${currency} ${amount.toFixed(2)}`;
}
function checkout() {
const currency = "EUR";
return formatPrice(19.5, currency);
}
console.log(checkout()); // "EUR 19.50"Exercises
Exercise
What does this program print, and why? const color = "blue"; function paint() { return color; } function scene() { const color = "red"; return paint(); } console.log(scene());
Show answer
It prints "blue". JavaScript uses lexical scope, so paint resolves color from where paint is written, which is the top level. The color declared inside scene is local to scene and is not in paint's scope chain, even though scene calls paint.
Exercise
Inside function outer you declare const b = 1, and inside a nested function inner you declare const c = 2. Which of these lines throws a ReferenceError: reading b inside inner, reading c inside outer (after inner is defined), or reading b inside outer?
Show answer
Only reading c inside outer throws. An inner scope can see bindings in its enclosing scopes, so inner can read b and outer can read b. Outer scopes cannot see bindings declared in inner scopes, so c is unreachable from outer.
Exercise
An object has a property total and a method sum() whose body is return total + 1. There is no variable named total anywhere. What happens when you call obj.sum(), and how do you fix it?
Show answer
It throws a ReferenceError because total is resolved as a variable through scope, and object properties are not variables. Fix it by writing return this.total + 1 (or referencing the object directly), which uses property lookup on the object that this refers to.