0

Could someone please explain the following ES6 code?

function magic(...nums) { let sum = 0; nums.filter(n => n % 2 == 0).map(el => sum+= el); return sum; }

17th May 2021, 5:51 AM
Prashandip Limbu
Prashandip Limbu - avatar
2 Respostas
+ 5
-magic(...nums) <==> indefinite number of parameters to a function and access them in an array. -filter(n => n % 2 == 0) <==> creates a new array with all el that passes the test implemented by the provided function. -map(el => sum += el) <==> creates a new array populated with the results of calling a provided function on every el in the calling array.
17th May 2021, 7:04 AM
Apongpoh Gilbert
Apongpoh Gilbert - avatar
+ 1
ES6 allow you to do the same behavior (returning sum of even numbers from passed ones as arguments) with a single line/loop (technically filter do one loop, and map do another one), and avoiding two temporary arrays creation: const magic = (...nums) => nums.reduce((r,v) => v%2 ? r : r + v,0);
17th May 2021, 8:47 AM
visph
visph - avatar