Closure function example and write program in JavaScript?
A closure function is a function that has access to variables in its outer scope, even after the outer function has returned. This is useful for maintaining state and for creating private variables. Here’s an example in JavaScript:
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
const add5 = outerFunction(5);
console.log(add5(3)); // 8
In this example, the outerFunction
returns the innerFunction
. The innerFunction
has access to the x
argument of the outerFunction
, even after the outerFunction
has returned. This means that we can store the returned innerFunction
in a variable (add5
in this case), and use it later to add 5 to another number.