Scope & Closures
Scope decides where in your code a variable can be seen and used. A closure is what happens when a function remembers the variables from the place it was created, even after that place has finished running. Together they explain how JavaScript keeps data private and why some bugs happen.
Three levels of scope
- Global scope: variables declared outside any function or block. Every part of the program can see them.
- Function scope: variables declared inside a function exist only inside that function.
- Block scope:
letandconstdeclared inside curly braces (anif, a loop, or a bare block) exist only inside those braces.
const school = "Moi Girls"; // global scope
function showClass() {
const form = "Form 3"; // function scope
if (true) {
const stream = "East"; // block scope
console.log(school, form, stream);
}
console.log(school, form);
// console.log(stream); would throw ReferenceError: stream is not defined
}
showClass();
// console.log(form); would throw ReferenceError: form is not defined
When JavaScript meets a name, it looks in the current scope first, then the one around it, and so on up to the global scope. This chain of lookups is the scope chain. If the name is found nowhere, you get a ReferenceError.
Shadowing
An inner scope may declare a variable with the same name as an outer one. The inner variable shadows (hides) the outer one inside its scope, and the outer one is untouched:
const leader = "Kamau";
function meeting() {
const leader = "Njeri";
console.log(leader);
}
meeting();
console.log(leader);
Shadowing is legal but can confuse readers, so use distinct names when you can.
Closures
A function in JavaScript carries a link to the scope where it was created. If a function is returned from another function, it still has access to the outer function's variables, even though the outer function has already finished. That combination of a function and its remembered variables is a closure.
function makeCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
console.log(counterA());
console.log(counterA());
console.log(counterA());
console.log(counterB());
Each call to makeCounter creates a fresh count variable and a new inner function that closes over it. Normally a function's local variables disappear when it returns, but here the inner function still refers to count, so it stays alive. counterA and counterB each have their own private count, which is why counterB() starts again at 1.
What closures are good for
Private data. Variables inside a closure can't be reached from outside except through the functions you choose to expose:
function createWallet(owner) {
let balance = 0;
return {
deposit(amount) {
balance += amount;
return `${owner} now has KES ${balance}`;
},
getBalance() {
return balance;
}
};
}
const wallet = createWallet("Neema");
console.log(wallet.deposit(500));
console.log(wallet.deposit(250));
console.log(wallet.balance);
console.log(wallet.getBalance());
wallet.balance is undefined because balance is not a property of the object; it lives only in the closure. Nobody can set it to a million shillings by accident.
Function factories. A function can build customised functions:
function makeMultiplier(factor) {
return (n) => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(7), triple(7));
Closures also power event handlers and timers: a click handler written inside a function can still use that function's variables when the click happens much later.
The classic loop trap: var vs let
This puzzle catches many developers. setTimeout runs a callback later (after 100 milliseconds here):
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var:", i), 100);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log("let:", j), 100);
}
With var there is only one i for the whole loop. By the time the callbacks run, the loop has finished and i is 3, so all three closures see 3. With let, each round of the loop gets its own j, so each closure remembers a different value. One more reason to prefer let. (Why the callbacks wait is explained in Callbacks & the Event Loop.)
Assigning to a name you never declared, such as total = 5; without let or const, silently creates a global variable in old, non-strict scripts, and throws a ReferenceError in strict mode and modules. Always declare your variables, and keep as few globals as possible.
Key points
- Scope is where a variable is visible: global, function or block (
let/constin braces). - Lookups move outward along the scope chain; outer code can't see inner variables.
- A closure is a function plus the variables it remembers from where it was created.
- Closures give private state (counters, wallets) and function factories.
- In loops,
letcreates a new variable each round;varshares one.
Tip: use the ← and → keys to move between pages.
