Sub topic 2
Understanding Scope
Every variable in JavaScript is visible in some parts of your program and invisible in others. The region where a name can be used is called its scope. To understand how var, let, and const differ, you first need a clear picture of what scope is, how scopes nest, and how JavaScript finds a variable when you use its name.
This chapter assumes you can write and call functions, use if statements and for loops, and run code in a browser console or Node.js. It covers the general model of scope. The chapters after this one explain how each keyword fits into that model.
What Scope Means
When you declare a variable, JavaScript creates a binding: a link between a name such as count and a storage slot that holds a value. Scope is the part of the source code where that binding can be reached by its name.
JavaScript has three main kinds of scope:
| Kind of scope | Created by | Bindings live until |
|---|---|---|
| Global scope | The top level of a classic script | The page or process ends |
| Function scope | Every function body, including its parameters | The function call finishes, unless a closure keeps them alive |
| Block scope | Any pair of braces `{ }` that forms a statement block | The block finishes, unless a closure keeps them alive |
ES modules add a fourth kind, module scope. Top-level declarations in a module are private to that module. They are not global. A later chapter on globalThis returns to this distinction.
Here is a short program that touches all three main kinds:
const appName = 'Inventory'; // global scope
function report(items) { // function scope: items and count live here
const count = items.length;
if (count > 0) { // block scope: first lives here
const first = items[0];
console.log(`${appName}: ${count} items, first is ${first}`);
}
// console.log(first); // ReferenceError: first is not defined
}
report(['bolt', 'nut']); // Inventory: 2 items, first is boltInside the if block, the code can read first, count, items, and appName. After the block closes, first is gone. Outside the function, only appName and report exist.
Scopes Nest Inside Each Other
Scopes form a tree. The global scope is the root. Each function creates a child scope, and each block inside it creates a grandchild scope, and so on. Code in an inner scope can see bindings from every scope that contains it. Code in an outer scope can never see into an inner one.
When you use a name, JavaScript resolves it by walking outward:
- Look in the current scope.
- If the name is not there, look in the scope that encloses it.
- Repeat until the global scope is reached.
- If the name is still not found, throw a
ReferenceError.
This outward path is called the scope chain.
The lookup stops at the first match. This rule has two consequences you will meet often: shadowing, and errors from names that were never declared.
Failed lookups
If no scope in the chain declares the name, reading it throws an error:
function outer() {
function inner() {
return missingName; // not declared anywhere
}
return inner();
}
try {
outer();
} catch (e) {
console.log(e.name); // 'ReferenceError'
console.log(e.message); // 'missingName is not defined'
}Assigning to an undeclared name works differently from reading one. In non-strict code, assigning to an undeclared name can silently create a global variable. That trap gets its own chapter later.
Shadowing
If an inner scope declares a name that also exists in an outer scope, the inner binding shadows the outer one. Inside the inner scope, the outer binding cannot be reached by that name.
const level = 'outer';
function inspect() {
const level = 'function';
{
const level = 'block';
console.log(level); // 'block'
}
console.log(level); // 'function'
}
inspect();
console.log(level); // 'outer'There are three separate bindings named level, one per scope. Shadowing never changes the outer variable. It only hides it.
Shadowing is legal, but it can mislead readers. A common bug is to declare a variable inside a block when you meant to update the outer one:
let status = 'pending';
function finish(success) {
if (success) {
let status = 'done'; // new binding that shadows the outer one
}
return status;
}
console.log(finish(true)); // 'pending', not 'done'Removing let inside the if turns the line into an assignment to the outer status, which is probably what the author wanted. Linters such as ESLint have a no-shadow rule that flags these cases.
Scope Is Lexical
JavaScript uses lexical scope, also called static scope. A function's scope chain is fixed by where the function is written in the source code. Where it is called from makes no difference.
const label = 'global';
function show() {
console.log(label);
}
function caller() {
const label = 'local to caller';
show(); // show was written at the top level, so it sees the global label
}
caller(); // 'global'If JavaScript used dynamic scope, show would print 'local to caller'. It doesn't. Because scope is lexical, you can work out what any name refers to just by reading the code around it. This is what makes the predictions in the rest of this tutorial possible.
Functions Remember Their Scope: Closures
Because scope is lexical, a function keeps access to the variables of the scope it was created in, even after that outer function has returned. The function together with the scope it remembers is called a closure.
function makeCounter() {
let count = 0; // lives in makeCounter's function scope
return function () {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
const other = makeCounter();
console.log(other()); // 1: each call to makeCounter creates a new scopeThe count binding outlives the call to makeCounter because the returned function still refers to it. Each call creates a fresh function scope, so next and other each have their own count. Closures matter a great deal when variables are declared inside loops, and the chapter on loops and closures shows how the choice of keyword changes the result.
What Counts as a Block
A block is a group of statements wrapped in braces. These all create a block:
- The body of
if,else,for,while, anddo...while try,catch, andfinallybodiesswitchbodies (the wholeswitchshares one block, not one percase)- A bare pair of braces used as a statement
Some braces do not create a block scope:
- Object literals.
{ a: 1 }is an expression that builds an object. It is not a scope. - Function bodies. These create a function scope. Function scope is a superset of block scope:
let,const, andvarall stay inside a function body. - Class bodies. These have their own rules for fields and methods, which this tutorial doesn't cover.
The switch rule surprises people. Every case shares one scope:
function describe(kind) {
switch (kind) {
case 'a': {
const message = 'first'; // braces give this case its own block
return message;
}
case 'b': {
const message = 'second'; // no clash, because it's a separate block
return message;
}
default:
return 'unknown';
}
}
console.log(describe('a')); // 'first'
console.log(describe('b')); // 'second'Without the extra braces, both const message declarations would sit in the same switch block. The script would then fail to load with a SyntaxError about a duplicate declaration.
Function parameters belong to the function scope. A catch clause's error parameter, such as e in catch (e), belongs to the catch block only.
How the Three Keywords Fit In
Not every keyword respects every kind of scope. This is the main difference between the three keywords:
| Keyword | Confined by a function body? | Confined by a block? |
|---|---|---|
| `var` | Yes | No |
| `let` | Yes | Yes |
| `const` | Yes | Yes |
A var declared inside an if block belongs to the enclosing function, or to the global scope if no function encloses it. let and const stay inside the nearest block. The next two chapters look at each side of this table in detail, with examples of where the difference changes program behavior.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Reading a block-scoped variable after its block ends | `ReferenceError` | Declare the variable in the outer scope and assign it inside the block |
| Redeclaring a name in an inner block when you meant to update the outer one | The outer value never changes | Remove the keyword so the line becomes an assignment |
| Expecting a function to see variables from where it is called | It sees variables from where it is defined | Pass the value in as a parameter |
| Treating object-literal braces as a scope | Confusing code, no actual scope | Remember that only statement blocks and functions create scopes |
| Relying on top-level names in modules being global | Other scripts can't see them | Export them, or attach them to `globalThis` explicitly |
The first fix in the table is a common pattern:
function pickDiscount(isMember) {
let discount; // declared in the function scope
if (isMember) {
discount = 0.1; // assigned inside the block
} else {
discount = 0;
}
return discount;
}
console.log(pickDiscount(true)); // 0.1
console.log(pickDiscount(false)); // 0Exercises
Exercise
Predict the output of this program and explain each line. const x = 'global'; function f() { const x = 'f'; function g() { console.log(x); } return g; } function h() { const x = 'h'; const fn = f(); fn(); } h(); console.log(x);
Show answer
It prints 'f' and then 'global'. g is defined inside f, so lexical scope makes g look up x in its own scope (not found), then in f's scope, where it finds 'f'. The fact that g is called from inside h is irrelevant, so h's x is never consulted. The final console.log runs at the top level and sees the global x.
Exercise
This function always returns 0, even for large orders. Explain why using scope terms and fix it. function shippingCost(total) { let cost = 0; if (total < 50) { let cost = 5; } return cost; }
Show answer
The inner let cost = 5 declares a new binding in the if block that shadows the function-scoped cost. The assignment never reaches the outer variable, and the inner binding disappears when the block ends, so the function returns the outer value 0. (Large orders are supposed to return 0, but small orders return 0 as well, which is the real bug.) Fix it by removing let inside the block so it reads cost = 5;. That line now assigns to the outer binding, and shippingCost(20) returns 5.
Exercise
Which of these create a new scope for a const declared directly inside them: (1) the braces of an if statement, (2) the braces of an object literal, (3) a function body, (4) a single case label in a switch without extra braces?
Show answer
(1) Yes, it is a block. (2) No, object literals are expressions, and you can't declare variables inside them. (3) Yes, a function body creates a function scope. (4) No, all cases share the one block of the switch body. You need to wrap a case in its own braces to give it a separate scope.