← All lessons
How closures work
A function that remembers
counter.js
function makeCounter() { let count = 0; return function inc() { count += 1; return count; };} const c1 = makeCounter();c1(); // 1c1(); // 2const c2 = makeCounter(); // a new scope, count = 0Build some counters then move count outside
Counters 0 / 4
counter.js
// count inside: every call makes a new onefunction makeCounter() { let count = 0; return () => { count += 1; return count; };}counter.js
// count outside: one for every counterlet count = 0;function makeCounter() { return () => { count += 1; return count; };}The var-in-a-loop bug and why let fixes it
Each callback and the i it reads
Console
loop.js
// var: one i for the whole loopfor (var i = 0; i < n; i++) { setTimeout(() => console.log(i));} // let: a new i for every passfor (let i = 0; i < n; i++) { setTimeout(() => console.log(i));}Topics
Next: How garbage collection works
Open lesson