What is closure in JavaScript?
In JavaScript, a closure is a function that has access to variables in its outer scope, even after the outer function has returned. This means that the closure can “remember” the values of its outer scope even after the function has finished executing.
Closures are created when a function is declared inside another function. The inner function has access to all the variables and functions declared in the outer function, and can reference them even after the outer function has returned.
Closures are often used to create private variables, because the closure can access variables that are not directly accessible from the outside. They are also useful for creating functions that can “remember” their state, because the closure can retain access to variables even after the outer function has finished executing.
Here is an example of how a closure can be used to create a private variable:
function createCounter() {
let count = 0;
return function() {
return ++count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
In this example, the createCounter
function returns a closure that increments and returns a private count
variable. The counter
variable retains access to the private count
variable even after the createCounter
function has returned.