Is it true that a closure is created in the following cases for foo
, but not for bar
?
Case 1:
In none of these examples is a closure created.
The second would create a closure if you actually created a function and did something with it, now you just create a function and then throw it away. Same as adding a line 3+8;
, you create a number, and then throw it away.
A closure is simply a function which references variables from its creation environment in its body, a canonical example is an adder:
function createAdder(x) { //this is not a closure
return function(y) { //this function is the closure however, it closes over the x.
return y + x;
}
} //thus createAdder returns a closure, it's closed over the argument we put into createAdder
var addTwo = createAdder(2);
addTwo(3); //3