FrontendJavaScriptClosuresES6

JavaScript Closures Explained with Real-World Examples

Closures are one of the most powerful and misunderstood features in JavaScript. Let me demystify them with practical examples.

Abdur Razzak

Abdur Razzak

Full-Stack Web Developer

May 26, 2026 7 min read

What Is a Closure?

A closure is a function that remembers the variables from its outer scope even after that outer function has finished executing. In JavaScript, every function creates a closure over the variables available when it was defined.

A Simple Example

Imagine a counter factory function that returns an increment function. The returned function keeps a private reference to the count variable. Each call to the factory creates an independent counter — this is closure in action.

Real-World Use Cases

Closures power many JavaScript patterns: module patterns for private state, memoization for caching expensive results, event handlers that capture loop variables, and currying for partial function application.

The Classic Loop Bug

The famous loop-closure bug happens when you use var in a for loop and create functions inside it. All functions share the same variable and print the same final value. Fix it by using let, which creates a new binding per iteration, or wrap the function in an IIFE.

Share this article

All posts
#JavaScript#Closures#ES6
Abdur Razzak — Full Stack Web Developer

Full-Stack Expert

MERN · React · Next.js · WordPress