Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading