In JavaScript, a closure is a function that has access to the variables in its lexical scope, even when the function is executed outside of its lexical scope.
Here’s an example of a closure in JavaScript:
function makeCounter() { let count = 0; return function() { count++; return count; } } const counter = makeCounter(); console.log(counter()); // 1 console.log(counter()); // 2 console.log(counter()); // 3
In this example, the makeCounter
function returns a function that increments and returns a count variable. The count variable is defined in the lexical scope of the makeCounter
function, but the returned function can still access and modify it, even when it is executed outside of that scope.
This is possible because the returned function maintains a reference to the variables in its lexical scope, even after the makeCounter
function has finished executing. This is known as a “closure.”
Closures are often used to create private variables and methods in JavaScript, as well as to create function factories and curried functions.