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

Abdur Razzak
Full-Stack Web Developer
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.
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.
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 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.