Belajar
← 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 = 0

Build some counters then move count outside

Where count livesInside makeCounterOutside, shared
Counters 0 / 4

counter.js

// count inside: every call makes a new onefunction makeCounter() {  let count = 0;  return () => {    count += 1;    return count;  };}

The var-in-a-loop bug and why let fixes it

Declare i withvarlet
Loop lengthn = 3
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