Closure:
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables. Whenever a function is called, a new scope is created for that call. The local variable declared inside the function belongs to that scope; they can only be accessed from that function.
Example:
function add(n) {
var b = n;
function result(m) {
var a = m;
return a+b;
}
return result;
}
var x=add(2);
console.log(x(3));
Output: 5
Here we have two functions.
- add() creates a local variable called b and returns the result() function.
- The result() function is an inner function that is defined inside add() and is only available within the body of the add() function. Note that the result() function has local variable a.
However, since inner functions have access to the variables of outer functions, result() can access the variable b declared in the parent function, add(). If result() were to have its own b local variable, it would use this instead. The result() function return sum of the a and b value.
In our example, the result() function had preserved the value of b when the add() function was executed, and continued to preserve (closure) it.