JS Closure
Let’s learn the concept of closure in javascript. before learning closure let’s discuss about lexical scoping.
function init() {
var name = 'Mozilla'; // name is a local variable created by init
function displayName() {
alert(name); // use variable declared in the parent function
}
displayName();
}
init();
in this above example, function init() creates local variable name and displayName() function. although displayName doesn’t consist the local variable but it can access the outer function variable. when we run this program, we can clearly see the alert displaying the name which is declared in it’s parent function. This is example of lexical scoping.
Closure
consider this code example:
function makeFunc() {
var name = 'Muskan';
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
The reason is that functions in JavaScript form closures. A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. In this case, myFunc
is a reference to the instance of the function displayName
that is created when makeFunc
is run. The instance of displayName
maintains a reference to its lexical environment, within which the variable name
exists. For this reason, when myFunc
is invoked, the variable name
remains available for use, and "Muskan" is passed to alert
.
Another code example:
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
In this example, we have defined a function makeAdder(x)
, that takes a single argument x
, and returns a new function. The function it returns takes a single argument y
, and returns the sum of x
and y
.
In essence, makeAdder
is a function factory. It creates functions that can add a specific value to their argument. In the above example, the function factory creates two new functions—one that adds five to its argument, and one that adds 10.
add5
and add10
are both closures. They share the same function body definition, but store different lexical environments. In add5
's lexical environment, x
is 5, while in the lexical environment for add10
, x
is 10.