Lessons in this course (16)

5. Closures

Intermediate★ Must knowLesson 5 of 16

A closure is a function bundled with references to the variables of the scope in which it was created; it keeps them alive after that scope has returned.

js
function createCounter() {
  let count = 0;                      // private state
  return {
    increment: () => ++count,
    getCount: () => count,
  };
}
const counter = createCounter();
counter.increment(); counter.increment();
counter.getCount();                   // 2 — count is not accessible directly

// Function factory
const multiplier = factor => n => n * factor;
const double = multiplier(2);
double(5);                            // 10

// Classic loop problem
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i));   // 3 3 3 — one shared 'i'
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j));   // 0 1 2 — new 'j' per iteration

Uses: data privacy/encapsulation, function factories, memoisation, debounce/throttle, event handlers, module pattern, partial application/currying. Risk: unintentionally retaining large objects (memory leaks).