← Back to Roadmap

Closures

Medium

In plain terms

When you define a function inside another function, the inner function can access variables from the outer function. That access does not disappear when the outer function returns—the inner function "closes over" those variables and keeps them alive. That combination of function plus captured variables is called a closure.

Closures are useful for creating private data (variables that only your function can see), for factories that create customized functions, and for callbacks that need to remember context. Understanding closures helps you avoid bugs and write cleaner code.

What you need to know

  • Function remembers outer scope
  • Creates private state
  • Created on every function call

Try it yourself

Copy the code below and run it in your browser console or a code editor:

function createCounter() {
  let count = 0;  // "closed over"
  return function() {
    count++;
    return count;
  };
}

const counter = createCounter();
counter();  // 1
counter();  // 2
counter();  // 3

// Private variable
function createPerson(name) {
  return {
    getName: () => name,
    setName: (n) => { name = n; }
  };
}

Why this matters

Closures are one of the most asked JavaScript topics. You may be asked to write a closure, fix a loop-with-closure bug, or explain private data with closures.

How it connects

Closures rely on scope (variables, let/const) and functions. They appear in callbacks, React (hooks), and module patterns. Understanding closures helps with this, call/apply/bind, and async callbacks.

Interview focus

Be ready to explain these; they come up often in JS interviews.

  • Definition: function that "remembers" its outer scope even after that scope has finished.
  • Use cases: private variables, factory functions, callbacks that need context, partial application.
  • Classic loop bug: var in loop + closure; fix with let or IIFE.

Learn more

Dive deeper with these trusted resources: