Can you explain me the JS code ? How its working?

Advertisements
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 its working step by step. I want to visualize that.

we know the map has this Signature,

array.map(function(currentValue, index, arr), thisValue)

By this can you explain me the code above ?

>Solution :

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

Leave a ReplyCancel reply