Popular Searches
Popular Course Categories
Popular Courses

Closures

25 mins Modern JavaScript (ES6+)

Closures in React JS

Course: React JS Training

Topic: Closures

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why closures matter

In JavaScript, a function is not just a list of instructions. When you create a function, the language quietly bundles it together with the variables that exist around it. This bundle travels with the function wherever the function goes, even to places where those variables would normally be out of reach. That behaviour is called a closure, and it is one of the ideas that separates people who merely type JavaScript from people who understand it.

Closures are not an optional advanced topic. They run under the bonnet of almost everything you will write:

  • Every event handler you attach to a button is a closure over the variables it uses.
  • Every callback you pass to setTimeout, map, filter or forEach is a closure.
  • Private data and module patterns in JavaScript are built with closures.
  • In React, hooks such as useState and every handler inside a component depend on closures working exactly the way they do.

For this React training course specifically, closures are the bridge between "I know the syntax" and "I understand why React behaves the way it does". When a component seems to remember a value, or a handler seems to use an old value, the explanation is always the same: a closure captured something, and you need to know what.

2. Closures in simple words

Here is the whole idea in one sentence: a closure is a function that remembers the variables from the place where it was created, even after that outer function has finished running.

A closure is a function packed together with the variables it needs from its birthplace. The function carries that memory for as long as the function itself is alive.

Two clarifications keep this definition honest:

  • A closure is not a feature you switch on. It happens automatically every time a function is created inside another function and is later used outside it.
  • A closure remembers variables, not frozen copies of values. If the remembered variable changes later, the closure sees the new value. The counter example below will make this very clear.

Think of it as luggage. The inner function is a traveller, and the outer variables it uses are packed into its suitcase. The traveller may go anywhere in the program, but the suitcase goes too.

3. Key terms before the examples

Closures borrow the vocabulary of scope, so it pays to have the words precise before the code starts.

TermPlain meaning
ScopeThe set of variables a piece of code is allowed to see.
Global scopeVariables visible from anywhere in the program.
Function scopeVariables declared inside a function, visible only within it.
Block scopeVariables declared with let or const inside a block between braces.
Lexical scopeScope decided by where code is written, not where it is run.
Outer functionThe function that contains another function.
Inner functionThe function defined inside another function.
Free variableA variable used by the inner function but declared outside it.
ClosureThe inner function plus the outer variables it keeps alive.

The word lexical sounds academic but it is not. It simply means "relating to the written text". JavaScript decides what a function can see by looking at where the function sits in the source code, not by following where the function is called from. That single fact explains almost everything about closures.

4. Scope and the lexical environment

Before closures make sense, variable lookup must make sense. When your code uses a name, JavaScript searches for it in a fixed order:

  1. First among the current function's own variables.
  2. Then in the function that encloses it, and the one that encloses that, moving outward.
  3. Finally in the global scope.
const level1 = "global";

function outer() {
  const level2 = "outer";

  function inner() {
    const level3 = "inner";
    console.log(level3); // "inner"  — found in the current function
    console.log(level2); // "outer"  — found one level up
    console.log(level1); // "global" — found two levels up
  }

  inner();
}

outer();

The console prints inner, then outer, then global. The inner function never received these values as arguments; it simply reached outward through the chain of scopes it was born into.

This chain of "who can see what" is called the lexical environment. A closure is what happens when part of that chain is kept alive for a function that has left home.

5. The structure of a closure

Almost every closure you will ever meet has the same three-part shape:

  • An outer function declares a variable.
  • An inner function uses that variable.
  • The outer function returns the inner function, or hands it to something else such as a timer or an event listener.
function makeKeeper() {
  // Part 1: a variable only this function can see
  const secret = "kept safe by the closure";

  // Part 2: an inner function that uses the variable
  function keeper() {
    return secret;
  }

  // Part 3: the inner function leaves the outer function
  return keeper;
}

const keep = makeKeeper();

console.log(keep()); // "kept safe by the closure"

The same shape written with arrow functions is shorter but identical in behaviour:

const makeKeeperArrow = () => {
  const secret = "kept safe by the closure";
  return () => secret;
};

console.log(makeKeeperArrow()()); // "kept safe by the closure"

Notice that makeKeeper has finished long before keep() is called. By every intuitive rule, secret should be gone. It is not gone, because the returned function still needs it.

6. How a closure works, step by step

Let us follow one closure through its whole life with a counter, the most famous closure example in JavaScript.

function makeCounter() {
  let count = 0;

  function increase() {
    count = count + 1;
    return count;
  }

  return increase;
}

const counter = makeCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
  1. makeCounter() runs. It creates the variable count with the value 0 inside its own scope.
  2. The inner function increase is created. Because it is written inside makeCounter, it is linked to that scope for life.
  3. makeCounter returns increase and finishes. Normally its variables would now be thrown away.
  4. But increase — now stored in counter — still refers to count. So JavaScript keeps count alive in memory.
  5. Each call counter() runs increase, which reads and updates that same surviving count.
  6. No code outside makeCounter can read or change count. The only door is counter.

The function plus its preserved variables — that bundle is the closure. And because the closure preserves the variable itself and not a snapshot of its value, count can grow from 1 to 2 to 3. If closures stored copies, every call would return 1 forever.

7. A first worked example: the greeting maker

Here is a gentle example with a parameter instead of a local variable. The outer function takes a value, and the returned function remembers it.

function makeGreeter(greeting) {
  return function (name) {
    return greeting + ", " + name + "!";
  };
}

const sayHello = makeGreeter("Hello");
const sayNamaste = makeGreeter("Namaste");

console.log(sayHello("Ada"));    // "Hello, Ada!"
console.log(sayNamaste("Ravi")); // "Namaste, Ravi!"

What is happening here:

  • makeGreeter("Hello") runs once, creates the variable greeting holding "Hello", and returns a function that closes over it.
  • makeGreeter("Namaste") runs again, creating a completely separate greeting and a second closure.
  • name is not part of the closure at all; it is an ordinary parameter supplied at call time.

So sayHello and sayNamaste are two functions built from the same code, carrying two different memories.

8. Private state: a small wallet

Closures give you something no plain object can: data that outside code cannot touch. In this wallet, balance exists only inside the closure shared by three methods.

function makeWallet(startingBalance) {
  let balance = startingBalance; // invisible from outside

  return {
    deposit(amount) {
      if (amount > 0) {
        balance = balance + amount;
      }
      return balance;
    },
    withdraw(amount) {
      if (amount > 0 && amount <= balance) {
        balance = balance - amount;
      }
      return balance;
    },
    getBalance() {
      return balance;
    }
  };
}

const wallet = makeWallet(100);

console.log(wallet.getBalance()); // 100
wallet.deposit(50);
console.log(wallet.getBalance()); // 150
wallet.withdraw(30);
console.log(wallet.getBalance()); // 120

console.log(wallet.balance);      // undefined — there is no direct way in

Three points worth pausing on:

  • balance is not a property of the returned object, so wallet.balance is undefined. The value can be read or changed only through the three methods.
  • All three methods were created inside the same call of makeWallet, so they share one closure and therefore one balance.
  • The rules live next to the data: withdraw refuses amounts that would push the balance negative, and nothing can bypass that check.

9. Every call creates its own closure

A common misunderstanding is that a closure is created once for the whole program. It is not. A closure is created every time the outer function runs, and each closure gets its own fresh variables.

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

const first = makeCounter();
const second = makeCounter();

console.log(first());  // 1
console.log(first());  // 2
console.log(second()); // 1 — a separate variable entirely
console.log(first());  // 3 — unaffected by second
Shared between first and secondSeparate for each
The code of makeCounterThe count variable: one per call
The code inside the returned arrow functionThe closure itself, with its own memory

This is why closures work so well as factories: the definition is written once, but every product carries its own private state.

10. Closures in loops: the classic trap

Sooner or later every JavaScript developer meets this trap. Three timers are scheduled in a loop, and all three print the same wrong number.

for (var i = 0; i < 3; i++) {
  setTimeout(function () {
    console.log("var:", i);
  }, 100);
}

// Logs:
// var: 3
// var: 3
// var: 3

Why does this happen?

  • var creates one single variable i for the entire loop.
  • All three callbacks close over that same one variable.
  • The timers fire after the loop has finished, by which time i is 3.

The modern fix is to declare the loop variable with let, which gives each iteration its own binding:

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

// Logs:
// let: 0
// let: 1
// let: 2

Each callback now closes over its own i, so each prints its own number. The older manual fix is worth seeing once, because it shows closures being used deliberately to create a copy:

for (var i = 0; i < 3; i++) {
  ((current) => {
    setTimeout(() => console.log("copy:", current), 100);
  })(i);
}

// Logs: copy: 0, copy: 1, copy: 2

The outer arrow function runs immediately with the current value of i, and its parameter current becomes a fresh variable per iteration.

Aspectvar in the looplet in the loop
How many variables existOne for the whole loopOne per iteration
What the callbacks close overThe same variable, seen at its final valueEach iteration's own variable
Typical logged output3, 3, 30, 1, 2

11. Factory functions: closures doing real work

A factory function builds and returns a function configured at creation time. The configuration lives in the closure, so every product remembers its own settings.

function makeMultiplier(factor) {
  return (number) => number * factor;
}

const double = makeMultiplier(2);
const triple = makeMultiplier(3);

console.log(double(10)); // 20
console.log(triple(10)); // 30

A more realistic factory stores two settings and applies them on every call:

function makePriceFormatter(currencySymbol, taxRate) {
  return (price) => {
    const withTax = price * (1 + taxRate);
    return currencySymbol + withTax.toFixed(2);
  };
}

const formatINR = makePriceFormatter("₹", 0.18);

console.log(formatINR(500)); // "₹590.00"
console.log(formatINR(99));  // "₹116.82"

Why this pattern is useful:

  • The symbol and the tax rate are supplied once; every later call stays short and readable.
  • You can create formatINR, formatUSD or any other variant from the same code without repeating yourself.
  • The settings cannot be swapped or corrupted from outside, because they live inside the closure.

12. A realistic example: the shopping cart

Putting the ideas together: private data, several methods sharing one closure, and behaviour rules next to the data they protect.

function makeCart() {
  const items = []; // private to this closure

  return {
    add(name, price) {
      items.push({ name: name, price: price });
      return items.length;
    },
    total() {
      return items.reduce((sum, item) => sum + item.price, 0);
    },
    summary() {
      return items.map((item) => item.name + ": ₹" + item.price).join(", ");
    }
  };
}

const cart = makeCart();

cart.add("Keyboard", 1500);
cart.add("Mouse", 700);

console.log(cart.summary()); // "Keyboard: ₹1500, Mouse: ₹700"
console.log(cart.total());   // 2200
console.log(cart.items);     // undefined — the array is private

The array items is reachable only through add, total and summary, because all three methods closed over it when makeCart ran. There is no way for other code to insert an item without a price or to empty the cart behind the methods' backs. That combination of data plus the functions that guard it is exactly what closures are for.

13. Closures and React: why this course cares

In React, a component function runs again on every render, and every function created inside it — handlers, callbacks, custom hook logic — is a closure over the props and state of that particular render.

import { useState } from "react";

function LikeButton() {
  const [likes, setLikes] = useState(0);

  function handleClick() {
    // handleClick closes over `likes` from this render
    setLikes(likes + 1);
  }

  return <button onClick={handleClick}>Likes: {likes}</button>;
}

export default LikeButton;

Each render runs LikeButton again, producing a new likes variable and a new handleClick that closes over it. The handler always sees the value from its own render — that is the closure at work, and it is why hooks behave predictably once you read them as closures.

Two practical notes connect this page to the rest of your training:

  • When a function is created once and reused across renders — a timer or an event listener registered on mount, for example — its closure keeps the values of that first render. If the code inside later reads state, it may read an old value. Recognising this as a closure, not a React bug, is most of the battle.
  • You may meet older tutorials that store a mounted flag inside a closure to guard against updates; modern React features have replaced that pattern, so treat it as history rather than advice.

For habits that keep closures inside hooks predictable, the notes on React hooks best practices are a useful companion to this page.

14. Closures in everyday callbacks

Part 1 built the idea from the ground up. Now let us see closures doing the daily work of a web developer. The most common closures are the ones you never notice: the small anonymous functions you hand to array methods, timers and event listeners.

const cutoff = 1000;
const prices = [450, 1200, 800, 1500];

const costly = prices.filter((price) => price > cutoff);

console.log(costly); // [1200, 1500]

The arrow function inside filter uses cutoff, a variable declared outside it. That arrow is a closure: it carries cutoff with it into filter's internal machinery. The same thing happens with event listeners:

<button id="saveBtn">Save</button>
const saveBtn = document.querySelector("#saveBtn");
const draft = "My unsaved changes";

saveBtn.addEventListener("click", () => {
  console.log("Saving: " + draft);
});

The listener stays registered for the whole life of the page, and the variable draft stays alive with it for just as long. Every click runs a function that still remembers a variable from code that finished executing long ago. That is a closure in production, and it is completely normal.

15. Real-world pattern: debounce

A debounce function delays an action until the user has stopped doing something for a moment — perfect for a search box where you want to wait until typing pauses. The private timer id lives in a closure, invisible to the rest of the program.

function makeDebounce(delay) {
  let timerId = null;

  return function run(fn) {
    if (timerId !== null) {
      clearTimeout(timerId); // cancel the previous waiting call
    }
    timerId = setTimeout(() => {
      timerId = null;
      fn();
    }, delay);
  };
}

const searchInput = document.querySelector("#search");
const runSearch = makeDebounce(500);

searchInput.addEventListener("input", () => {
  runSearch(() => console.log("Searching for:", searchInput.value));
});

What the closure is doing here:

  • timerId is created once, inside makeDebounce, and only the returned run can touch it.
  • Every keystroke calls run, which cancels the previous timer and starts a new one.
  • The search fires only when 500 milliseconds pass with no new keystroke.

No global variable holds the timer id, and no other code can cancel or read it. The closure is the private wiring cupboard.

16. Real-world pattern: memoization

Memoization means remembering the results of previous calls so the same input never computes twice. A closure is the natural place to hide the cache.

function makeMemoized(fn) {
  const cache = new Map();

  return (argument) => {
    if (cache.has(argument)) {
      return cache.get(argument);
    }
    const result = fn(argument);
    cache.set(argument, result);
    return result;
  };
}

function slowSquare(n) {
  // imagine heavy work here instead of a simple multiply
  return n * n;
}

const fastSquare = makeMemoized(slowSquare);

console.log(fastSquare(12)); // 144 — computed by slowSquare
console.log(fastSquare(12)); // 144 — served from the cache

The cache Map is reachable only through the returned function, so it cannot be edited, cleared or replaced from outside. Every memoized function made from makeMemoized gets its own independent cache, because every call creates a fresh closure — the rule from Part 1 applied to real work.

17. Common mistakes and how to fix them

Expecting a frozen copy of the value

A closure preserves the variable, not the value it had when the function was created.

let count = 0;
const showCount = () => console.log(count);

count = 99;
showCount(); // 99, not 0

The correct way: if you genuinely need a snapshot, copy the value into a new variable at capture time, for example by passing it through a parameter of a wrapper function.

let count = 0;
const snapshot = ((value) => () => console.log(value))(count);

count = 99;
snapshot(); // 0 — a true copy from capture time

Shadowing the outer variable

Re-declaring the same name inside the inner function creates a brand-new local variable, and the closure variable silently stops being updated.

function makeTally() {
  let total = 0;
  return () => {
    let total = 0; // a new local — the outer total never moves
    total = total + 1;
    return total;
  };
}

const tally = makeTally();
console.log(tally()); // 1
console.log(tally()); // 1 — always the inner copy

The correct way: remove the inner let total declaration. Then the function reads and updates the closure variable, and the calls return 1, 2, 3 as intended.

Forgetting to return or store the inner function

A closure only survives if the inner function leaves the outer function and is kept alive somewhere.

function makeCounterWrong() {
  let count = 0;
  function increase() {
    count = count + 1;
  }
  // nothing is returned — increase and count simply die here
}
makeCounterWrong();

The correct way: return increase (or store it in a variable, an object or a listener). Once nothing can reach the inner function, JavaScript is free to discard the whole closure — and eventually will.

Keeping large data alive by accident

A long-lived closure keeps everything it captures alive. A listener registered on window that captures a huge array will pin that array in memory for the whole session.

// Risky: bigData can never be collected while the page lives
window.addEventListener("resize", () => {
  console.log(bigData.length);
});

The correct way: capture only what the handler needs. Copy the small value out, or remove the listener when it is no longer required with removeEventListener, which lets the closure and its captured data be collected together.

18. Best practices for writing closures

  • Prefer const and let over var everywhere, especially in loops, so each iteration gets its own binding and the classic trap cannot occur.
  • Use a factory naming style such as makeCounter, makeDebounce, makeMemoized so a reader instantly knows the function returns something that remembers.
  • Keep the captured state small. Capture the one or two values the inner function truly needs, not entire large objects "just in case".
  • Keep the closure's lifetime under control: remove event listeners and clear timers when the feature that created them is done.
  • Use closures for privacy — state that outside code should not touch — instead of inventing global variables.
  • Avoid deep nesting. A function inside a function inside a function is legal, but three levels of captured state is hard to reason about; flatten it into a factory with a clear API.
  • Remember the React connection: every handler in a component closes over that render's props and state. When a callback "sees an old value", diagnose it as a closure question first.

19. Practical project: a stopwatch built from closures

This small project puts private state, shared closure methods and event listeners into one working page you can build in minutes.

Step 1: create the files

Make a folder with two files: index.html and stopwatch.js.

Step 2: write the HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Closure Stopwatch</title>
</head>
<body>
  <p id="display">0.0 s</p>
  <button id="startBtn">Start</button>
  <button id="stopBtn">Stop</button>
  <button id="resetBtn">Reset</button>
  <script src="stopwatch.js"></script>
</body>
</html>

Step 3: write the closure factory

function makeStopwatch() {
  let startTime = null;    // when the current run began
  let elapsedBefore = 0;   // milliseconds saved from earlier runs
  let running = false;

  return {
    start() {
      if (!running) {
        startTime = performance.now();
        running = true;
      }
    },
    stop() {
      if (running) {
        elapsedBefore = elapsedBefore + (performance.now() - startTime);
        running = false;
      }
    },
    reset() {
      startTime = null;
      elapsedBefore = 0;
      running = false;
    },
    seconds() {
      const total = elapsedBefore + (running ? performance.now() - startTime : 0);
      return total / 1000;
    }
  };
}

All three state variables are private. The four methods were created inside one call of makeStopwatch, so they share one closure and therefore one stopwatch.

Step 4: wire the buttons

const watch = makeStopwatch();
const display = document.getElementById("display");

document.getElementById("startBtn").addEventListener("click", watch.start);
document.getElementById("stopBtn").addEventListener("click", watch.stop);
document.getElementById("resetBtn").addEventListener("click", watch.reset);

setInterval(() => {
  display.textContent = watch.seconds().toFixed(1) + " s";
}, 100);

Step 5: run and observe

Open index.html in the browser. Start, stop and reset work, and the display updates ten times a second. Notice two closure details: the methods can be passed straight to addEventListener because they never use this — they close over their variables instead — and nothing outside stopwatch.js can corrupt the timing state.

20. Practice Exercises

  • Write makeAccumulator() that returns a function; each call adds its argument to a private total and returns the new total.
  • Write makeIdGenerator(prefix) that returns a function producing "user-1", "user-2" and so on, with the counter private to the closure.
  • Write makeOnce(fn) that returns a function running fn only the first time; every later call does nothing.
  • Build makeTeamScore() whose returned object has addTeamA(points) and addTeamB(points), with both methods sharing one private score object.
  • Take the var loop-and-setTimeout trap from Part 1 and fix it two ways: with let, and with an immediately-invoked wrapper that copies the value.
  • Extend the stopwatch project with a lap() method that stores lap times in a private array and a laps() method that prints them.

21. Interview Questions and Answers

What is a closure in one sentence?

A closure is a function bundled with the outer variables it uses, so those variables stay alive and accessible even after the outer function has finished running.

Why does the inner function still see the outer variables after the outer function returns?

Because the inner function still references them. As long as any code can reach the inner function, JavaScript keeps the captured variables in memory instead of discarding them.

Does a closure capture values or variables?

Variables. The closure holds a live link to the variable itself, so later changes to that variable are visible to the closure. To get a frozen value you must copy it explicitly, for example through a wrapper function's parameter.

What is a free variable?

A variable used inside a function but declared outside it — in some enclosing scope. Free variables are exactly what a closure preserves.

How do closures create private state?

By declaring variables inside an outer function and returning methods that use them. Because nothing outside can reach those variables directly, the only access is through the returned methods, as in the wallet and cart examples.

Why does var in a loop with setTimeout print the final value, and how does let fix it?

var creates one variable shared by the whole loop, so every callback closes over the same variable and sees its final value. let creates a fresh binding per iteration, so each callback closes over its own copy and prints its own number.

Give a practical use of closures beyond counters.

Debounce and memoization are the standard answers: both need private state — a timer id or a cache — that survives between calls but must be invisible to the rest of the program.

Do closures cause memory leaks?

They can contribute to one. A long-lived closure keeps every captured variable alive, so capturing large data in a listener that lives for the whole session pins that data in memory. The fix is to capture only what is needed and to remove listeners when they are no longer required.

What happens when two closures are created by the same outer function call?

They share the same captured variables, because both were linked to that one call's scope. Two separate calls of the outer function produce separate closures with independent variables.

How are closures related to React hooks?

Every render of a component runs the component function again, and each handler or callback created in that render closes over that render's props and state. Understanding hooks as closures explains why a handler sees the values from its own render, and why a long-lived callback can appear to hold an old value.

When would you choose a closure over a class for private data?

For small, function-shaped features — counters, debouncers, memoizers, factories — a closure is lighter and needs no new. For larger structures with many methods and inheritance needs, a class is clearer. Both can achieve privacy; closures do it by scope, classes do it with private fields.

What is variable shadowing and why does it matter for closures?

Shadowing is declaring a local variable with the same name as an outer one. Inside the inner function the name refers to the local variable, so the closure variable is never touched — a silent logic bug that appears when code "runs but the total never changes".

22. Quick Revision Checklist

  • A closure is a function plus the outer variables it uses, kept alive after the outer function finishes.
  • Scope is decided by where code is written (lexical), not where it is called.
  • Closures capture variables, not snapshots of values.
  • Every call of the outer function creates a fresh closure with its own variables.
  • let in loops gives each iteration its own binding; var shares one.
  • Private state, factories, debounce, memoization and event handlers are all closure patterns.
  • Long-lived closures keep captured data alive — capture little, and clean up listeners.
  • Shadowing an outer variable silently breaks the closure link.
  • In React, every render creates new closures over that render's props and state.

23. Official Documentation and Further Reading

Closures themselves belong to core JavaScript, and the best next step is applying them inside React, where this course is heading. These companion reads fit this page:

Conclusion

A closure is small in definition and enormous in consequence: a function that remembers the variables of the place where it was born. With that one idea you can explain private state, factory functions, debounce, memoization, the loop-and-timer trap, and the behaviour of every handler and hook you will write in React.

Carry three habits forward from this page. First, when you create an inner function, ask what it captures and how long that captured state must live. Second, when state seems to be shared, or seems not to be shared, check which outer function call created each closure. Third, when a value looks "stale" inside a callback, suspect the closure before suspecting the framework. Master this, and the rest of the Modern JavaScript module — and the React training that follows it — will feel less like memorising rules and more like reading the language's own logic.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp