Introduction
JavaScript closures are often considered confusing, especially for beginners. Many developers memorize definitions without truly understanding how closures work.
In this article, we will explain JavaScript closures in a simple and practical way, using examples that actually make sense.
What Is a Closure?
A closure is created when a function remembers variables from its outer scope, even after that outer function has finished executing.
In simpler terms, a closure allows a function to access variables that were available when the function was created.
Basic Closure Example
function outerFunction() {
let message = "Hello from closure";
function innerFunction() {
console.log(message);
}
return innerFunction;
}
const myFunction = outerFunction();
myFunction();
Even though outerFunction has finished running,
innerFunction still remembers the message variable.
Why Closures Work
JavaScript functions form closures because the language uses lexical scoping.
This means a function can access variables defined:
- Inside itself
- In its parent function
- In the global scope
Closures in Real-World Code
Closures are commonly used in real applications, including:
- Event handlers
- Callbacks
- Timers
- State management
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
counter();
counter();
Each call updates the same count variable stored inside the closure.
Common Closure Mistakes
1. Assuming Variables Are Copied
Closures do not copy variables — they keep a reference to them.
2. Memory Leaks
Keeping closures around longer than necessary can cause memory issues if they reference large objects.
Final Thoughts
Closures are not magic — they are a natural result of how JavaScript handles scope.
Once you understand closures, many advanced JavaScript concepts become much easier.