A closure is a function that has access to the variables in the scope in which it was defined, even after that scope is no longer in use. In other words, a closure "closes over" the variables it references, allowing the function to continue to access and use those variables.
Here is an example of a closure in JavaScript:
function makeCounter() { let count = 0; return function() { return count++; } } let counter = makeCounter(); console.log(counter()); // Output: 0 console.log(counter()); // Output: 1 console.log(counter()); // Output: 2
In this example, the
makeCounter
function returns an anonymous function that keeps track of a count variable. When the returned function is invoked, it increments and returns the count variable. Because the returned function has access to the variables in the scope of the makeCounter
function, it can "remember" the current count value even after the makeCounter
function has finished executing. This is an example of closure in action.Another example for closure is when we want to use a callback function inside a for loop.
for (let i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 1000); }
In this example, the function passed to
setTimeout
is invoked after the loop has finished executing. If the function did not close over the variable i, it would log 3
three times as the variable i would be equal to 3 after the loop is done, but because the function closes over variable i, the function will log the correct values of i.Closures are useful in a variety of situations, such as for creating private variables and methods in JavaScript, creating function factories, and for creating callbacks that can be passed to other functions.
Loading Comments...