Sitemap
Aakash Jain

Aakash Jain

JavaScript Closures Made Simple

2 min readSep 15, 2025

--

Closures are one of the most powerful — and sometimes confusing — concepts in JavaScript. If you’re learning frontend development or diving deeper into React and TypeScript, understanding closures is a must. Let’s break it down step by step.

1. What is a Closure?

In simple terms, a closure is when a function remembers variables from its outer scope, even after that scope has finished executing.

👉 Think of it as a backpack 🎒 — a function carries variables with it wherever it goes.

2. Basic Example

function outer() {
let counter = 0; // variable in outer scope
  function inner() {
counter++;
console.log(counter);
}
return inner;
}
const fn = outer();
fn(); // 1
fn(); // 2
fn(); // 3

✅ Here, inner function remembers counter from outer, even though outer has already finished executing.

3. Why Are Closures Important?

Closures are everywhere in JavaScript:

  • Data Privacy: Hide variables from the global scope.
  • Callbacks & Event Listeners: Functions need access to surrounding data.
  • Functional Programming: Used in currying, higher-order functions.
  • React Hooks: Hooks like useState and useEffect rely on closures.

4. Real-World Example

Example: Private Variables

function createBankAccount(initialBalance) {
let balance = initialBalance;
  return {
deposit: function(amount) {
balance += amount;
return balance;
},
withdraw: function(amount) {
balance -= amount;
return balance;
},
getBalance: function() {
return balance;
}
};
}
const account = createBankAccount(100);
console.log(account.deposit(50)); // 150
console.log(account.getBalance()); // 150

Here, balance is private — it can’t be accessed directly but can be modified using the returned methods.

5. Common Mistakes

Example: Using var in Loops

for (var i = 1; i <= 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
// Output: 4, 4, 4

❌ Problem: var is function-scoped, so all callbacks share the same i.

Get Aakash Jain’s stories in your inbox

Join Medium for free to get updates from this writer.

✅ Fix with let (block scope):

for (let i = 1; i <= 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
// Output: 1, 2, 3

6. Closures in React

Closures are at the heart of React Hooks.

function Counter() {
const [count, setCount] = useState(0);
  useEffect(() => {
const timer = setInterval(() => {
setCount(c => c + 1); // closure remembers latest value of c
}, 1000);
return () => clearInterval(timer);
}, []);
return <h1>{count}</h1>;
}

Here, the callback inside setInterval uses a closure to remember c.

7. Conclusion

  • A closure is simply a function remembering variables from its outer scope.
  • They enable data privacy, callbacks, functional patterns, and React hooks.
  • Once you master closures, many confusing JavaScript behaviors start making sense.

--

--