Closures

Topic 5 of 6 in Functions6 min readBeginnerFree course

Overview

When a function is created inside another function, it keeps access to the outer function’s variables — even after the outer function has finished. That combination of a function and the variables it remembers is called a closure.

JavaScript
function makeGreeter(greeting) {
  return (name) => `${greeting}, ${name}!`;
}

const hello = makeGreeter('Hello');
const namaste = makeGreeter('Namaste');
hello('Asha');   // 'Hello, Asha!'
namaste('Ravi'); // 'Namaste, Ravi!'

By the time hello('Asha') runs, makeGreeter has long since returned. Normally its local variable greeting would be gone. But the arrow function it returned still needs greeting, so JavaScript keeps it alive. Think of it as a backpack the inner function carries around, holding the variables it was born next to.

Why it works

Closures follow directly from two rules you’ve already learned:

  1. Lexical scope — a function can see the variables around the place it was written.
  2. Functions are values — they can be returned and stored, and called later from somewhere else.

Put together: a function created inside another can be returned to the outside world, and it still sees what it saw when it was written. JavaScript keeps those variables in memory for as long as the inner function exists.

Private state

Closures are a simple way to hide data. Nothing outside makeCounter can change count directly:

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

const counter = makeCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.current();   // 2
counter.count;       // undefined — there's no way in except the three functions

Each call gets its own variables

Every time you call makeCounter, a new count is created, and only the functions from that call can see it:

makeCounter declares let count = 0 and returns a function that increments it. Calling makeCounter twice creates two functions, a and b, each remembering its own count: after a(); a(); b(); a has count 2 and b has count 1.

JavaScript
const a = makeCounter();
const b = makeCounter();
a.increment(); // 1
a.increment(); // 2
b.increment(); // 1 — b has its own count

Practical uses

Function factories

A function that builds customised functions:

JavaScript
function makeDiscount(percent) {
  return (price) => price * (1 - percent / 100);
}

const tenOff = makeDiscount(10);
const halfPrice = makeDiscount(50);
tenOff(200);    // 180
halfPrice(200); // 100

Callbacks that remember context

Event handlers and timers often need values from when they were set up:

JavaScript
function setupButton(button, message) {
  button.addEventListener('click', () => {
    alert(message); // remembered from setupButton's call
  });
}

setupButton(saveBtn, 'Saved!');
setupButton(deleteBtn, 'Deleted!');

Run only once

JavaScript
function once(fn) {
  let done = false;
  let result;
  return (...args) => {
    if (!done) {
      done = true;
      result = fn(...args);
    }
    return result;
  };
}

const init = once(() => console.log('Setting up…'));
init(); // 'Setting up…'
init(); // nothing — already done

Remembering results (memoisation)

JavaScript
function memoize(fn) {
  const cache = new Map();
  return (n) => {
    if (!cache.has(n)) cache.set(n, fn(n));
    return cache.get(n);
  };
}

const slowSquare = (n) => { /* imagine heavy work */ return n * n; };
const fastSquare = memoize(slowSquare);
fastSquare(9); // calculated
fastSquare(9); // from the cache

A common pitfall

Closures capture variables, not values. If the variable changes later, the function sees the new value:

JavaScript
let rate = 0.1;
const tax = (price) => price * rate;
tax(100); // 10
rate = 0.2;
tax(100); // 20 — the closure reads rate when it runs

That matters in loops. With let in a loop, each iteration gets its own variable, so this prints 0, 1, 2:

JavaScript
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}

With var, it prints 3, 3, 3 — all three callbacks share one variable. Another reason to prefer let.

Closures and memory

Because a closure keeps its variables alive, a long-lived closure that holds something large (a big array, a DOM element) keeps that alive too. This rarely matters, but if you add event listeners or intervals that capture big data, remember to remove them (removeEventListener, clearInterval) when you no longer need them, so the memory can be freed.

Exercise

Build a counter

Write makeCounter() so that each counter it returns keeps its own count. Bonus — let makeCounter(start) take an optional starting number.

JavaScript
function makeCounter() {
  // your code here
}

const a = makeCounter();
a(); // 1
a(); // 2
const b = makeCounter();
b(); // 1

Summary

  • A closure is a function plus the variables it could see when it was created.
  • The remembered variables stay alive as long as the function does — even after the outer function has returned.
  • Each call to the outer function creates a fresh set of variables.
  • Closures let you keep private state without classes, and power factories, callbacks and once-only functions.
  • Closures capture variables, not values — use let in loops.