Closures in JavaScript
A closure allows an inner function to remember and access variables from its outer function, even after the outer function has finished execution.
What is a Closure?
A closure is created when an inner function remembers the variables of its outer function.
The inner function can continue to access those variables even after the outer function has completed its execution.
Simple Definition
A closure is a function together with the variables from its surrounding scope.
The inner function remembers variables from its outer scope.
Example 1: Basic Closure
In this example, the inner function can access the variable declared inside the outer function.
function outerFunction() {
let message = "Welcome to CIIT";
function innerFunction() {
console.log(message);
}
innerFunction();
}
outerFunction();
Welcome to CIIT
Example 2: Returning an Inner Function
A function can return another function. The returned function can still remember variables from the outer function.
function createMessage() {
let message = "Hello JavaScript";
return function() {
console.log(message);
};
}
let showMessage = createMessage();
showMessage();
Hello JavaScript
Example 3: Counter Using Closure
Closures can be used to create private variables. Here, the counter variable is maintained by the returned function.
function createCounter() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
let counter = createCounter();
counter();
counter();
counter();
1
2
3
Important Points
• A closure is created when an inner function accesses variables from an outer function.
• The inner function remembers those variables even after the outer function finishes.
• Closures are useful for creating private data and maintaining state.
• Closures are commonly used in callbacks, event handlers and JavaScript applications.
Summary
Closures allow a function to remember and access variables from its surrounding scope. They are useful for maintaining state, creating private variables and building reusable JavaScript functionality.