Scope and closures
Scope defines where a variable is visible. Understanding it prevents two kinds of problems: using a variable that does not exist at that point and accidentally modifying a variable you did not mean to touch. With let and const the scope is block scope: a variable exists only inside the braces where it is declared. Functions create their own scope: what you declare inside a function is not visible from outside.
const globalName = 'global';
function show() {
const local = 'local';
console.log(globalName, local); // global local
}
show();
// console.log(local); // ReferenceError: local is not defined
if (true) {
let insideBlock = 'block';
console.log(insideBlock); // block
}
// console.log(insideBlock); // ReferenceError
for (let i = 0; i < 2; i++) {}
// console.log(i); // ReferenceError: i only lives in the loopThe scope chain
When you use a name, JavaScript looks for it first in the current scope and, if it does not find it, goes up to the scope that contains it and so on up to the global one. This is called the scope chain. An inner function can read the variables of the functions that surround it, but not the other way around. If an inner variable has the same name as an outer one, the inner one hides it (shadowing), which usually causes confusion; avoid repeating names.
Closures: functions that remember
A closure happens when an inner function still has access to the variables of the outer function even after the outer one has finished. The function carries its environment with it. This lets you create private variables that nobody can modify from outside, and factories of configured functions. It is not magic: the function simply keeps a reference to the variables it needs.
function createCounter() {
let count = 0; // private: only the inner functions can reach it
return {
increment() {
count++;
return count;
},
current() {
return count;
}
};
}
const a = createCounter();
const b = createCounter();
a.increment();
a.increment();
b.increment();
console.log(a.current(), b.current()); // 2 1
// count is not accessible from outside
function multiplier(factor) {
return (n) => n * factor;
}
const triple = multiplier(3);
console.log(triple(5)); // 15Each call to createCounter creates its own count, which is why a and b are independent. This pattern is the basis of many techniques: keeping state without global variables, creating specialized functions like triple and handling events in the browser, which you will see in week 7. A classic mistake is creating functions inside a loop with var: they all share the same variable. With let each turn has its own copy.
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map((f) => f())); // [ 3, 3, 3 ]
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map((f) => f())); // [ 0, 1, 2 ]Where closures are used
Although the name sounds theoretical, you will use closures almost every day without realizing it. Every time you write an event handler that uses a variable declared outside it, you are using a closure. The same happens with setTimeout when its callback reads variables from the function that scheduled it, and with functions that return other configured functions, such as an identifier generator or a call limiter. If at some point a function behaves mysteriously, ask yourself which variables it captures and whether someone modified them in the meantime; the answer is almost always there.
function createIdGenerator(prefix) {
let next = 1;
return () => `${prefix}-${next++}`;
}
const userId = createIdGenerator('user');
const orderId = createIdGenerator('order');
console.log(userId(), userId(), orderId()); // user-1 user-2 order-1✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字