DEV Community

Satish
Satish

Posted on

Simplest Way to Understand Closures in JavaScript

A closure is when a function “remembers” variables from the place where it was created, even after that place (the outer function) has finished running.
Think of it like a backpack 🎒:

  • The inner function carries a backpack filled with variables from the outer function.
  • Even if the outer function is gone, the inner function still has access to those variables.

📘 Example

function outer() {
  let count = 0;   // variable inside outer function

  return function inner() {
    count++;       // inner function still remembers "count"
    console.log(count);
  };
}

const counter = outer(); 
counter(); // 1
counter(); // 2
counter(); // 3
Enter fullscreen mode Exit fullscreen mode
  • outer() runs once and creates count.
  • It returns inner(), which remembers count.
  • Every time you call counter(), it updates and prints the preserved value of count.

🎯 Why Closures Matter

  • Data privacy → You can hide variables from the outside world.
  • Maintain state → Useful for counters, caches, or remembering values.
  • Callbacks & async code → Closures let functions keep context when executed later.

👉 A closure is basically: “A function + the environment it was created in.”

Let’s make closures feel super intuitive with a real-world analogy:

🏪 Shopkeeper Analogy
Imagine you go to a small shop every day, and instead of paying immediately, you say:
“Put it on my tab.”

  • The shopkeeper is like the inner function.
  • Your tab (the running total) is like the variable inside the outer function.
  • Even after you leave the shop (outer function finishes), the shopkeeper remembers your tab. So every time you come back, the shopkeeper adds to your tab and shows you the updated amount. That’s exactly how a closure works — the inner function remembers and keeps updating variables from its original environment.

👨‍💻 Code Version of the Shopkeeper

function createTab() {
  let total = 0; // your tab

  return function buy(itemPrice) {
    total += itemPrice; 
    console.log("Your tab is now: " + total);
  };
}

const myTab = createTab();
myTab(50); // Your tab is now: 50
myTab(30); // Your tab is now: 80
myTab(20); // Your tab is now: 100
Enter fullscreen mode Exit fullscreen mode

Here, myTab is like the shopkeeper who remembers your running total (total) even though createTab() has already finished.

🎯 Key Takeaway
A closure is just a way for a function to remember values from where it was created — like a shopkeeper remembering your tab, or a backpack holding onto variables.

Top comments (0)