In JavaScript, a closure is a function that has access to the outer (enclosing) function’s scope even after the outer function has returned.
A closure is created when an inner function is defined inside an outer function and the inner function is returned or passed as a value. The inner function maintains a reference to the outer function’s scope, which means it has access to the outer function’s variables and arguments even after the outer function has completed execution.
Here is an example of a closure in JavaScript:
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
const addFive = outerFunction(5);
console.log(addFive(3)); // Output: 8
In this code, the outerFunction
function defines an inner function named innerFunction
and returns it. The innerFunction
function has access to the x
variable, which is defined in the outerFunction
function’s scope.
When the outerFunction
function is called with an argument of 5
, it returns the innerFunction
function. This returned function is assigned to the addFive
variable. When the addFive
function is called with an argument of 3
, it is able to access the x
variable, which has a value of 5
, and it returns the sum of x
and y
, which is 8
.
Closures are a powerful feature of JavaScript and are often used in functional programming to create higher-order functions (functions that operate on other functions). They can be useful for creating private variables, implementing function currying, and creating function factories.
I hope this helps! Let me know if you have any questions.