A closure is a function that has access to variables in its outer (enclosing) scope, even after the outer function has returned. Closures are a powerful feature of JavaScript that allows you to create functions with persistent state and private variables. In this answer, we’ll explore closures in depth with an example.
Example 1: Counter Function
Let’s start with a simple example of a closure that creates a counter function. This function will return a new number each time it is called, starting at 1 and increasing by 1 each time.
function createCounter() {
let count = 0;
return function() {
count++;
return count;
}
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
In this example, createCounter
is a function that returns another function. The inner function has access to the count
variable in the outer scope of createCounter
. Each time the inner function is called, it increments the count
variable and returns its new value.
When we call createCounter
, it returns a new instance of the inner function, which we assign to the counter
variable. We can then call counter
multiple times to get the next number in the sequence.