logo

Closures

An approachable explanation of closures, how they capture environments, and common use-cases.

Short explanation

A closure is a function that retains access to variables from its lexical scope even after the outer function has finished executing. This allows functions to remember and interact with the environment where they were created.

Syntax example

function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2

How JS handles it internally

When the inner function is created, JavaScript captures a reference to the surrounding lexical environment. The variables are stored on the heap if they outlive the stack frame, and the garbage collector removes them when there are no remaining references.

Diagram

diagram-placeholder

Related

πŸ”— Related:

FAQ

Q: Do closures cause memory leaks?

A: Not by themselves β€” closures keep references alive, but leaks occur when references persist unnecessarily (for example, global references or large data retained longer than needed).