DEV Community

Satish
Satish

Posted on • Edited on

Simplest Way to Understand Closures in JavaScript

A closure in JavaScript means:
A function remembers the variables from the place where it was created, even after that outer function has finished running.

Think of it like a function carrying a backpack 🎒 of variables from its parent scope.

1. Simple Real-World Example (Bank Account)

Imagine a bank account where only a few functions can access the balance.

function createAccount(initialBalance) {
  let balance = initialBalance;

  return function deposit(amount) {
    balance += amount;
    console.log("Balance:", balance);
  };
}

const myAccount = createAccount(1000);

myAccount(500); 
myAccount(200);

//Output:
//Balance: 1500
//Balance: 1700
Enter fullscreen mode Exit fullscreen mode

What happens?

createAccount(1000) runs.

  1. It creates a variable balance = 1000.
  2. It returns the deposit function.
  3. Normally balance should disappear after createAccount finishes.
  4. But because of closure, the deposit function remembers balance

👉 The function keeps access to balance even after the outer function finished.
That is Closure.

2. Another Real Example (Private Counter)

Suppose you want a counter that nobody can change directly.

function createCounter() {
  let count = 0;

  return function () {
    count++;
    console.log(count);
  };
}

const counter = createCounter();

counter();
counter();
counter();

//Output:
//1
//2
//3
Enter fullscreen mode Exit fullscreen mode

Here:

  • count is private
  • Only the returned function can access it
  • The function remembers count

Again → Closure

3. Very Simple Analogy

Think of a chef writing a recipe 🍲

  • The chef writes the recipe in the kitchen.
  • Later someone cooks it in another place.
  • But the recipe still remembers the ingredients from the kitchen. Similarly:
Function + Remembered Variables = Closure
Enter fullscreen mode Exit fullscreen mode

4. Why Closures Are Useful

Closures are commonly used for:

  1. Data privacy (private variables)
  2. Counters
  3. Event handlers
  4. Callbacks
  5. Functional programming Example in real apps:
  • Login sessions
  • API caching
  • React hooks
  • Module pattern

5. One-Line Definition (Interview Style)

A closure is created when a function remembers and accesses variables from its outer scope even after the outer function has finished executing.

One more easy example:

function outer() {
  let name = "Rahul";

  return function inner() {
    console.log(name);
  };
}

const fn = outer();
fn();
Enter fullscreen mode Exit fullscreen mode

What happens?

  1. outer() runs.
  2. Variable name is created.
  3. inner() is returned.
  4. Normally name should disappear ❌
  5. But inner() remembers it ✅

Output:
Rahul
👉 Because inner function remembers name → Closure.

Top comments (0)