Explain it simply
Explain it simply
Think of a building. A notice pinned up in the lobby can be read by people from every room. Writing on a whiteboard inside one room, though, is visible only to people in that room, not to anyone in the lobby. Scope works like those rooms: it decides where in your code a variable can be read.
In JavaScript the rooms are nested inside each other. From an inner room you can see what is written in the outer rooms, but never the other way round. Every function and every { } block forms a new room.
Problem → Why → Solution
The problem: total was added to, yet it is still 0
You write a function to add up a shopping cart. Inside it, prices are clearly being added to total, but when the function finishes and you print total, you get 0. There is no error and no warning. The whole problem lives in one small word: the let in front of total.
let total = 0;
function addItems(items) {
let total = 0; // a NEW total that hides the outer one
for (const item of items) {
total += item.price;
}
}
addItems([{ price: 5 }, { price: 7 }]);
console.log(total); // 0 — the outer total never changedWhy is it still 0?
The let total inside the function creates a new variable in the function's scope and hides the outer total; this is called shadowing. The loop updates only the inner total, which disappears when the function returns. The better fix is not to mutate the outer variable at all, but to return the result and write const total = addItems(items).
Core concept: four kinds of scope and the scope chain
Scope is the region of code where an identifier, such as a variable, function or class name, can be used. JavaScript has four main kinds. Global scope is the outermost and visible everywhere. Module scope is the top level of each ES module (a file using import/export); nothing in it is visible to other files unless exported. Function scope covers what is declared inside a function, and block scope covers the inside of if, for, while and plain { } braces.
The keyword decides which scope you get. let, const and class respect block scope and vanish when the closing brace is reached. var ignores blocks and lands in the nearest function (or the global) scope, which is why a var declared inside an if block can still be read after the block.
JavaScript uses lexical scope: what a function can see is decided by where its code is written, its nesting, not by where it is called from. When you use a name, the engine looks in the current scope first, then each enclosing scope outward until it reaches global. This path is the scope chain. If the name is found nowhere, you get a ReferenceError. The search only ever goes outward, never into inner scopes.
Declaring a variable in an inner scope with the same name as an outer one stops the search early and hides the outer variable; that is shadowing. It is legal, but as the problem section showed, it confuses readers. Global mutable variables that every file and function can change also couple distant parts of the code, and a value changed by one test leaks into the next. Parameters and module exports make those dependencies visible instead.
Looking up a name walks the scope chain outward
-----------------------------------------------
+-- global / module scope ------------------------------+
| globalVar |
| +-- function outer() -------------------------------+ |
| | outerVar | |
| | +-- function inner() ---------------------------+ | |
| | | innerVar | | |
| | | uses outerVar: inner -> outer (found) | | |
| | +-----------------------------------------------+ | |
| +---------------------------------------------------+ |
+-------------------------------------------------------+- Look in the current block/function
- Not found: move one scope outward
- Reach global; still missing = error
- The first match wins (shadowing)
You can always look outward, but never peek inward.
General pattern
const shared = value; // module/global scope
function name(param) { // function scope: param, local
const local = value;
if (condition) { // block scope
const temp = value; // gone after the closing brace
var leaked = value; // var escapes to function scope
}
return local; // shared, param, local, leaked visible
}Picture each scope as a set of braces. The innermost block sees everything outside it, but temp cannot be seen outside its block. var cuts through the block and ends up in the function scope.
Example: global, function, block and lexical scope
This example reads variables from each level of scope. Reading an out-of-scope name directly would throw a ReferenceError and stop the script, so those names are checked with typeof instead, which lets you run it and see every result. typeof returns "undefined" for an undeclared name instead of throwing.
// Global (top-level) scope
let globalVar = "I'm global";
function demoScope() {
// Function scope
var functionVar = "I'm in function";
if (true) {
// Block scope
let blockVar = "I'm in block";
var notBlock = "I'm function scoped"; // var ignores the block
console.log(globalVar); // OK: outer scope
console.log(functionVar); // OK: enclosing function
console.log(blockVar); // OK: same block
}
console.log(functionVar); // OK
console.log(notBlock); // OK: var escaped the if-block
console.log(typeof blockVar); // "undefined": blockVar is gone
}
demoScope();
console.log(globalVar); // OK
console.log(typeof functionVar); // "undefined": function scope is private
// Lexical scope: inner functions see outer variables
function outer() {
let outerVar = "outer";
function inner() {
let innerVar = "inner";
console.log(`${outerVar} + ${innerVar}`);
}
inner();
}
outer();Code breakdown
- Line 2
let globalVar = "I'm global";Declared at the top level, so every function in the file can read it. In a classic script it is global; in an ES module it lives in module scope.
- Lines 10-11
var notBlock = "I'm function scoped"; // var ignores the blockblockVar (let) lives only inside the if block, but notBlock (var) ignores the block and belongs to demoScope's function scope.
- Line 19
console.log(notBlock); // OK: var escaped the if-blockThe block has closed, yet notBlock is still readable. This var behaviour is the source of loop counters leaking out of their blocks.
- Line 20
console.log(typeof blockVar); // "undefined": blockVar is goneblockVar is no longer visible outside the if block. Writing console.log(blockVar) directly would throw a ReferenceError; typeof reports "undefined" instead.
- Line 33
console.log(`${outerVar} + ${innerVar}`);inner() has no outerVar, so the engine follows the scope chain up to outer() and finds it there. This works only because inner is written inside outer: lexical scope.
I'm global
I'm in function
I'm in block
I'm in function
I'm function scoped
undefined
I'm global
undefined
outer + innerScope and context (this) are different things
This lesson's title mentions "context", so it is worth separating the two. Scope decides where variable names are looked up and is fixed when the code is written. Context, the value of this, depends on how a function is called, for example which object it is called on, and is decided at run time. In the code below, the same function called through two objects gives a different this.label, while the label read from scope never changes.
const label = "module scope";
const box = {
label: "box property",
viaThis() {
return this.label; // context: decided by the call
},
viaScope() {
return label; // scope: decided by where the code is written
},
};
const other = { label: "other object", viaThis: box.viaThis };
console.log(box.viaThis()); // box property
console.log(other.viaThis()); // other object
console.log(box.viaScope()); // module scopeIn real projects
Where this shows up in real projects
Most JavaScript projects today are written as ES modules. Every file gets its own module scope, so two files can each have a helper with the same name without clashing, and only what you export is visible elsewhere. Before module systems, many script tags shared one global scope, and problems such as two libraries fighting over the name "$" were common.
Passing configuration into a function as a parameter, instead of reading a global, makes testing easier: each test supplies its own config without affecting the others. Values needed only for one loop iteration, declared with const inside the block, cannot leak out. ESLint's no-shadow rule warns about the kind of shadowing seen in the problem section, and TypeScript or ESLint also flag the use of undeclared variables.
Common mistakes
Common mistakes
1. Shadowing by accident
You meant to update the outer variable, but writing let or const again inside the function creates a new variable and the outer one never changes. Leave out the keyword if you only want assignment, or better, return the result.
2. Assigning to an undeclared variable
In a sloppy-mode script, writing count = 1; without let or const silently creates a new global variable. In ES modules and code with "use strict", it throws a ReferenceError instead. Always declare your variables.
3. var leaking out of a block
After for (var i = 0; i < 3; i++) {}, i is still around outside the loop with the value 3 and can collide with a later variable of the same name. With let, i exists only inside the loop.
Best practices
Best practices
- Declare each variable in the smallest scope that needs it.
- Pass values into functions as parameters and return results, rather than reading and writing globals.
- Do not reuse names across nested scopes; turn on ESLint's no-shadow rule.
Mini challenge
Mini challenge: an order summary with no globals
Write summarize(), which takes a list of orders and a config object as parameters and returns a summary string. Use no global mutable state, and keep temporary values inside block scope.
- Accept config ({ taxRate, currency }) as a parameter instead of reading a global
- Declare each order's lineTotal with const inside the loop block
- Round tax to 2 decimals and return a string like "items=2 subtotal=20.00 USD tax=2.00 USD"
- Call it with two different configs and show with typeof that lineTotal never leaks out
function summarize(orders, config) {
// TODO: read taxRate and currency from config (not from a global)
// TODO: let subtotal = 0
// TODO: loop over orders; declare lineTotal with const inside the loop
// TODO: round the tax to 2 decimals
// TODO: return "items=N subtotal=X.XX CUR tax=Y.YY CUR"
}
// TODO: print summarize(...) for a USD config with taxRate 0.1
// TODO: print summarize(...) for a EUR config with taxRate 0.05
// TODO: print typeof lineTotalExpected: One summary line per config, then undefined at the end: items=2 subtotal=20.00 USD tax=2.00 USD items=1 subtotal=30.00 EUR tax=1.50 EUR undefined
Show hint
You can destructure in the parameter list: function summarize(orders, { taxRate, currency }). Round with Math.round(x * 100) / 100 and display with toFixed(2).
Show solution
function summarize(orders, { taxRate, currency }) {
let subtotal = 0;
for (const order of orders) {
const lineTotal = order.qty * order.price; // lives for one iteration
subtotal += lineTotal;
}
const tax = Math.round(subtotal * taxRate * 100) / 100;
return (
`items=${orders.length} subtotal=${subtotal.toFixed(2)} ${currency} ` +
`tax=${tax.toFixed(2)} ${currency}`
);
}
const usd = { taxRate: 0.1, currency: "USD" };
const eur = { taxRate: 0.05, currency: "EUR" };
console.log(summarize([{ qty: 2, price: 4.5 }, { qty: 1, price: 11 }], usd));
console.log(summarize([{ qty: 3, price: 10 }], eur));
console.log(typeof lineTotal);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Scope decides where a variable is visible; the four kinds are global, module, function and block.
- let, const and class respect block scope; var cuts through blocks into the function scope.
- The scope chain searches only outward, and lexical scope is fixed by where code is written.
- Avoid shadowing and global mutable state, and do not confuse scope (variables) with context (this).
MDN — JavaScript Guide — MDN Web Docs