Closure in JavaScript – Explained with Real-Life Examples

javascript closures

I still remember the first time I stumbled upon the term JavaScript closures.” It felt like a word from another planet. Everyone around me seemed to nod knowingly, and I was just… lost.

If you’re here because you googled “what is a JavaScript closure” and ended up with ten tabs open full of confusing code snippets — trust me, I’ve been there. Let’s simplify it, one step at a time.

What is a JavaScript Closure

A JavaScript closure happens when a function remembers the variables from where it was created — even after that outer function has finished running.

Think of it like this
You have a backpack (your closure) that holds a few variables. Even if you move away from the place where you packed it, you can still access everything inside that backpack whenever you want.

Here’s a simple example to make sense of this:

function outerFunction() {
let counter = 0;

function innerFunction() {
counter ;
console.log(counter);
}

return innerFunction;
}

const count = outerFunction();

count(); // 1
count(); // 2
count(); // 3
JavaScript

Now, let’s pause here — what’s happening?

Even though outerFunction is done running, the innerFunction still remembers the variable counter.
That memory link is what we call a closure in JavaScript.

Importance Of Closures in JavaScript

Closures are one of the most powerful features in JavaScript. But honestly, I didn’t realize that until I started using them in real-world projects.

Here’s why JavaScript closures are such a big deal:

  • They preserve state between function calls.
  • They help encapsulate data, keeping variables private.
  • They allow modular and reusable code design.
  • They are the foundation of advanced JS patterns like currying, callbacks, and event handling.

Basically, if you want to master JavaScript, you can’t skip closures.

A Relatable Example — A Secret Counter

I remember once while building a web quiz app, I wanted a score variable that users couldn’t modify directly from the console. That’s when I realized — closures are perfect for this!

function createScore() {
let score = 0;

return {
increase: function() { score ; },
decrease: function() { score--; },
getScore: function() { return score; }
};
}

const game = createScore();

game.increase();
game.increase();
console.log(game.getScore()); // 2
JavaScript

Notice what’s happening here?
The score variable isn’t accessible from the outside. You can’t just type game.score and see it — it’s private. Only those functions (increase, decrease, getScore) can touch it.

That’s the power of JavaScript closure — creating private data in an otherwise public language.

Real-World Uses of JavaScript Closures

Here’s where I’ve seen JavaScript closures really shine in actual coding life:

1. Data Privacy in Web Apps

As shown above, closures allow you to hide implementation details while still exposing the parts that matter.

Think of it like how your phone shows you the camera button — not the complex code running behind it.

2. Event Listeners

Whenever you attach an event handler, closures are silently doing their job.

function setupButton() {
let count = 0;
document.getElementById('clickMe').addEventListener('click', function() {
count ;
console.log(`Button clicked ${count} times`);
});
}
JavaScript

Even after setupButton() finishes, the function inside addEventListener still remembers the count. Magic? Nope — closure. ✨

3. Timers and Async Code

When working with setTimeout() or promises, closures help preserve variable state across asynchronous calls.

4. Currying and Partial Functions

If you’ve ever used a function that returns another function, that’s closure at work again.

Common Mistakes

When I first played with JavaScript closures, I made a few rookie mistakes that cost me hours of debugging. Let’s save you that pain.

❌ Mistake 1: Expecting Variables to Reset Automatically

const add = (function() {
let counter = 0;
return function() {
counter = 1;
return counter;
}
})();
console.log(add()); // 1
console.log(add()); // 2
console.log(add()); // 3
JavaScript

❌ Mistake 2: Not Understanding Scope

Closures rely heavily on lexical scope — meaning a function remembers where it was defined, not where it was called.

How I Finally Understood JavaScript Closures

I used to visualize JavaScript closures like a house 🏠.
Each function is a room, and variables are the furniture.

When a function is created, it “locks in” the room it was built in — including all the furniture (variables) inside it. So, even when you walk out of that room, your function can still go back and grab what it needs.

Once I started visualizing it like that, closures just… clicked.

Handy Tip: Inspect Closures in Browser DevTools

If you’re using Chrome or Firefox, open DevTools → Sources → Scope.
When you pause on a breakpoint inside a nested function, you can literally see which variables are being “closed over.” It’s like peeking into the backpack I mentioned earlier.

This is a fantastic way to understand JavaScript closures in action — especially if you’re more of a visual learner.

Final Thoughts:

If there’s one takeaway from my journey with JavaScript closures, it’s this:
They’re not a trick question from a coding interview. They’re a real, practical concept that makes your JavaScript code more powerful, private, and flexible.

Once you stop thinking of closures as some abstract theory, and start seeing them as a natural part of how functions work — everything gets easier.

Want to learn more about javascript??, kaashiv Infotech Offers Front End Development CourseFull Stack Development Course, & More www.kaashivinfotech.com.

0 Shares:
You May Also Like