3 ms·
A little clearer, consider this example: function sumArray(arr){ return arr.reduce(function(accumulator, value){ return accumulator + v
by just2n 14y ago
A little clearer, consider this example:
function sumArray(arr){
return arr.reduce(function(accumulator, value){
return accumulator + value;
}, 0);
}
The inner function here is what we typically refer to as an anonymous function. However, closures can also be anonymous:
function sumArray(arr){
var sum = 0;
arr.forEach(function(value){
sum += value;
});
return sum;
}
Both of these do the same thing. One is a closure, the other isn't. The only difference is that the closure has a free variable.
The answer, in this SO link, says that the function 'f' is not a closure in the first example which isn't accurate. Consider the canonical wrong way to do it:
for (var i = 0; i < 10; i++){
setTimeout(function(){
console.log(i);
}, 100);
}
This function here (or rather functions) is anonymous and it is also closed over i because it is external to the function. It doesn't matter that i is global, because this code would behave the same if it were presented in global scope or inside a function somewhere. The fact that you get 10 10s printed is because the variable is manipulated by the loop and every closed function created is closed over the same variable. This answer argues awkwardly that free variables that are global don't count towards being closures.