Why didn't the variable disappear?
Why a local variable lives on after its function has finished.
count between calls. Someone's lying. Let's find out.Each function call creates an environment — a "box" with its local variables. Usually, once the function has finished, nobody needs the box, and the garbage collector throws it away. Hence the rule "local variables disappear".
But if a function was created inside and handed outside — returned, passed to a handler, put in an object — it holds a reference to that box. While the function lives, so does the box. The garbage collector removes only what can no longer be reached.
function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
a();
a();
console.log(a());
console.log(b());counts.An important detail: a function remembers the variable itself, not its value at creation time. If the variable changes later, the function sees the new value.
let rate = 1.1;
const toUsd = (eur) => eur * rate;
rate = 1.5;
console.log(toUsd(2));rate at call time — by then it was 1.5.What if you need to remember the value at creation time? Pass it as a parameter. A parameter is a new variable in a new box, and nobody outside can change it any more.
function makeGreeting(name) {
return () => "Hello, " + name;
}
let user = "Byte";
const greet = makeGreeting(user);
user = "Mittens";
console.log(greet());greet remembers the parameter name, not the outer user. Hence "Hello, Byte".The most famous JavaScript trap grows from the same rule: var in a loop. var creates one variable for the whole function: one box for every step. let in a for header creates a new box on each iteration. In real code, instead of () => i there's a click handler or a setTimeout — a function that runs later, long after the loop has finished.
const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withVar[0](), withVar[1](), withVar[2]());
console.log(withLet[0](), withLet[1](), withLet[2]());var look into one box — and it already holds 3. With let, each has its own.A box that outlives calls is a great place for a cache. If a function is slow, remember its result and hand it out instantly next time. Such wrappers are called memo — libraries and React are full of them.
function memo(slowFn) {
const cache = {};
return (n) => {
if (n in cache) return "from cache: " + cache[n];
cache[n] = slowFn(n);
return "computed: " + cache[n];
};
}
const square = memo((n) => n * n);
console.log(square(12));
console.log(square(12));
console.log(square(5));cache lives in the closure: invisible from outside, but it remembers everything already computed.Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.