console.log([1 , 2, 3 , 4 , 5].map((acc = 0 , num => acc = num)));
// output : [1, 3, 6, 10, 15]
I know closure has been applied here to this code but don't know how it's working, step by step - I want to visualize that.
We know the map has this Signature:
array.map(function(currentValue, index, arr), thisValue)
With this can anyone explain the code above to me?
CodePudding user response:
This is technically creating a closure, but the key part is that this is declaring a global variable acc
(unless acc
already exists in the current scope), initializing it with the value 0
, then using that inside the anonymous arrow function. By using the grouping operator and the comma operator, it's done inline.
console.log([1 , 2, 3 , 4 , 5].map((acc = 0 , num => acc = num)));
// output : [1, 3, 6, 10, 15]
console.log(acc, window.acc); // acc exists globally
It's equivalent to this:
acc = 0;
console.log([1 , 2, 3 , 4 , 5].map(num => acc = num));
// output : [1, 3, 6, 10, 15]
console.log(acc, window.acc); // acc exists globally
Note that in strict mode, unless you've declared the variable before, the program will fail.
"use strict";
console.log([1 , 2, 3 , 4 , 5].map((acc = 0 , num => acc = num)));
// output : ReferenceError: Can't find variable: acc
console.log(acc, window.acc); // acc doesn't exist because program exits
"use strict";
let acc;
console.log([1 , 2, 3 , 4 , 5].map((acc = 0 , num => acc = num)));
// output : [1, 3, 6, 10, 15]
console.log(acc, window.acc); // acc doesn't exist globally, but it does locally