Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Back to JavaScript
JavaScript Closures Explained with Examples

JavaScript Closures Explained with Examples

JavaScriptBy Muhammad Fareed
javascriptclosuresexamples

Short answer: a closure is a function that remembers the variables from the place where it was created, even after that outer function has finished running. Closures are how JavaScript gives you private state, callbacks that keep their context, and function factories.

A first example

function makeCounter() {
  let count = 0;            // lives in makeCounter's scope
  return function () {
    count += 1;
    return count;
  };
}

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

makeCounter has finished, yet the returned function can still read and change count. That link between the inner function and its surrounding variables is the closure. Calling makeCounter() again creates a separate count.

How a JavaScript closure keeps access to an outer variableOuter function: Declares a variable. Inner function: Defined inside it. Outer returns: Its call has finished. Closure: Inner still reads the variableOuter functionDeclares a variableInner functionDefined inside itOuter returnsIts call has finishedClosureInner still reads thevariable
Diagram: How a JavaScript closure keeps access to an outer variable.

How it works: lexical scope

JavaScript uses lexical scoping: a function can see variables from the scope in which it was written, not the scope from which it is called. When the function is created, it keeps a reference to that scope. As long as the function exists, those variables stay alive.

Practical uses of closures

1. Private variables

function createAccount(initial) {
  let balance = initial;
  return {
    deposit(amount) { balance += amount; },
    getBalance() { return balance; }
  };
}

const acc = createAccount(100);
acc.deposit(50);
console.log(acc.getBalance()); // 150
console.log(acc.balance);      // undefined, cannot be touched directly

2. Function factories

function multiplier(factor) {
  return (n) => n * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5), triple(5)); // 10 15

3. Callbacks and event handlers

function attach(button, label) {
  button.addEventListener("click", () => {
    console.log("Clicked:", label); // label is remembered
  });
}

4. Memoization

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

The classic loop mistake

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 100);
}
// prints 3, 3, 3

var is function-scoped, so all three callbacks share one i, which is 3 when the timers fire. Fix it with let, which creates a new binding for each iteration:

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

Closures and memory

A closure keeps the variables it uses alive. That is usually what you want, but a long-lived closure that references large objects (for example a handler that is never removed) can prevent memory from being freed. Remove event listeners you no longer need and avoid capturing more than necessary.

Common questions answered quickly

QuestionAnswer
Does every function create a closure?Technically yes, but it only matters when an inner function outlives its outer one.
Are closures slow?Not in normal use. Modern engines optimize them well.
Closure vs scope?Scope is where variables are visible. A closure is a function plus the scope it remembers.

Closures appear everywhere in asynchronous code. Continue with promises and async/await.

FAQs

Why is it called a closure?

The function "closes over" the variables in its surrounding scope, capturing them so they remain available later.

Can a closure change the outer variable?

Yes. It captures the variable itself, not a copy, so changes are visible to every function that shares it.

How do I test my understanding?

Predict the output of the loop example with var and then let, and explain why they differ.

Where are closures used in real projects?

In React hooks, event handlers, module patterns, debounce and throttle helpers, and almost every callback-based API.