Sub topic 2
What a Closure Is
This chapter assumes you know basic JavaScript syntax, can declare and call functions, and understand the difference between var, let, and const.
What a Closure Is
A closure is a function together with the lexical environment it was created in. When an inner function refers to a variable from an outer function, it keeps access to that variable even after the outer function has returned.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
const other = makeCounter();
console.log(other()); // 1Each call to makeCounter creates a new environment holding its own count. The returned function keeps a reference to that environment, so counter and other have separate state.
Closures Capture Variables, Not Snapshots
A closure holds a live link to the variable itself. It does not copy the variable's value. It reads whatever value the variable has at the moment the closure runs.
function makeGetter() {
let value = 1;
const get = () => value;
value = 2;
return get;
}
console.log(makeGetter()()); // 2A common error is to expect get to return 1 because that was the value when get was created.
The Classic Loop Bug and How to Fix It
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log('var:', i), 0);
}
// var: 3, var: 3, var: 3
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log('let:', j), 0);
}
// let: 0, let: 1, let: 2var is function-scoped, so all three callbacks share one i. The loop has finished by the time they run, so i is 3. let creates a new binding on each iteration, so each callback captures its own j. Before let existed, the fix was to wrap the body in a function that received i as a parameter.
Private State with Closures
Code outside a function cannot reach the variables inside it. Closures let you expose only the functions you choose.
function createAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
balance += amount;
return balance;
},
getBalance() {
return balance;
}
};
}
const account = createAccount(100);
account.deposit(50);
console.log(account.getBalance()); // 150
console.log(account.balance); // undefinedThe only way to change balance is through deposit.
Exercise
Rewrite for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } so that it logs 0, 1, 2 while keeping var.
Show answer
Wrap the callback in a function that receives the current value as a parameter: for (var i = 0; i < 3; i++) { (function (n) { setTimeout(() => console.log(n), 0); })(i); }. Each call creates a new scope with its own n.
Exercise
In createAccount, what does account.balance = 0; account.getBalance() return after the deposit above, and why?
Show answer
It returns 150. Setting account.balance adds a new property to the object. It does not touch the balance variable the closure holds.