Javascript Closure
Introduction
In JavaScript, a closure is a function that has access to the variables and scope of its outer function, even after the outer function has returned. This allows the closure to retain its state and continue to operate, even after its outer function has finished executing.
Example
Here is an example of a closure in JavaScript:
function outerFunction() {
let outerVariable = “Hello, world!”;
return function innerFunction() {
console.log(outerVariable);
};
}
let closure = outerFunction();
closure(); // logs “Hello, world!”
In the example above, the outerFunction defines a outerVariable variable and returns a innerFunction. The innerFunction has access to the outerVariable variable, even after the outerFunction has returned.
When the closure variable is assigned the return value of the outerFunction, it becomes a function that can access the outerVariable variable. When the closure function is called, it logs the outerVariable to the console.
Advantages of Closures
Closures have several advantages over other ways of retaining state in JavaScript: