π What is Closure in JavaScript?
In JavaScript, a closure is created when a function "remembers" variables from its outer lexical scope, even after the outer function has returned.
Closures enable inner functions to continue accessing variables from the outer function. This powerful concept is key to writing flexible and secure code.
Example of a Closure
function outerFunction() {
let outerVariable = "Hello from the outer scope";
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
const myClosure = outerFunction();
myClosure(); // Output: Hello from the outer scope
How it works:
-
outerFunction
defines a local variableouterVariable
. -
innerFunction
is declared insideouterFunction
and usesouterVariable
. - When
outerFunction()
is called, it returnsinnerFunction
. - Even though
outerFunction()
has completed, the returnedinnerFunction
still has access toouterVariable
.
This behavior is what we call a closure.
Why Use Closures?
Closures are useful when:
- You want to keep certain data private.
- You need to preserve a value between function calls.
- You work with asynchronous functions like
setTimeout
,setInterval
, or API calls.
Real-World Example: Counter
function createCounter() {
let count = 0;
return function () {
count++;
console.log(count);
};
}
const counter1 = createCounter();
counter1(); // 1
counter1(); // 2
const counter2 = createCounter();
counter2(); // 1
Each counter instance has its own independent count
value. This happens because each call to creates a new closure.
Summary
A closure is a function bundled with its lexical environment. It gives you the ability to:
- Maintain state across executions
- Hide and protect variables
- Work more efficiently with asynchronous or functional code
Closures are a core concept in JavaScript and are commonly used in practical applications like module patterns, callbacks, currying, and event handlers.
Read More
To see the original version of this blog with additional formatting and examples, visit:
https://webcodingwithankur.blogspot.com/2025/06/what-is-closure-in-javascript.html.html
Top comments (0)