A function returned from another keeps the variables it was created with. Two counters each keep their own count.
JavaScript · beginner · 8 min · 24 steps · free
function makeCounter() {
let count = 0;
return function increment() {
count = count + 1;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
counterA();
counterA();
console.log(counterA(), counterB());makeCounter already exists. This is called hoisting.makeCounter(). It gets its own variables.count is a local variable of this call of makeCounter.increment. increment uses count, so count must outlive this call.count lives on, reachable only through counterA.count is created with the value 0.makeCounter returns the function increment().makeCounter() has finished, so its variables are gone. The value it returned, function increment(), is stored in counterB.count from the first makeCounter call.count changes from 0 to 1.increment returns 1.increment() has finished, so its variables are gone.increment(). It gets its own variables. It can still use count from makeCounter() #1, which has already returned: the closure keeps it alive.count changes from 1 to 2.increment returns 2.increment() has finished, so its variables are gone.increment(). It gets its own variables. It can still use count from makeCounter() #1, which has already returned: the closure keeps it alive.count changes from 2 to 3.increment returns 3.increment(). It can still use count from makeCounter() #2, which has already returned: the closure keeps it alive.increment returns 1.Answer: No, only increment can. That is how closures make private state.
Answer: No
← Scope and Hoisting · Recursion →