JavaScript closures and scope

A closure is a function together with the variables from the scope where it was created. makeCounter creates a local variable count and returns functions that use it. Each call to makeCounter creates a separate count, so two counters never interfere. The variable is private: only the returned functions can reach it.

JavaScript
function makeCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    value: () => count,
  };
}

const a = makeCounter();
const b = makeCounter();
a.increment();
a.increment();
b.increment();
console.log(a.value(), b.value());

const withVar = [];
for (var i = 0; i < 3; i++) {
  withVar.push(() => i);
}
console.log(withVar.map((f) => f()).join(","));

const withLet = [];
for (let j = 0; j < 3; j++) {
  withLet.push(() => j);
}
console.log(withLet.map((f) => f()).join(","));
Read the full lesson