can you expain this code ? I can't able to understand ! | SoloLearn: Learn to code for FREE!

+8

can you expain this code ? I can't able to understand !

What is the output of the following code? function magic(...nums) { let sum = 0; nums.filter(n => n % 2 == 0).map(el => sum+= el); return sum; } console.log(magic(1, 2, 3, 4, 5, 6)); // Answer is 12 but how ?

6/12/2019 1:52:04 PM

+10

Injamul Mohammad Mollah filter()??? map()???? It takes me a week to solve this & I refuse to use any life-line (hint/unlock). This exercise is meant for next lesson I guess. function filter(n => n%2==0) try to check all nums for values that will give remainder 0 if divided by 2 filter(n => n %2 == 0) checks the objects "n" in nums with modulus operation and add the object with true result "el" in sum while discarding any false results, function map(el => sum +=el) works here to add up the filtered nums i.e 2,4,6 in simple terms here we go; var nums = [1,2,3,4,5,6], n = nums, sum = 0, el = 0; //function filter(n => n%2==0) for(let i=0; i<n.length; i++){ if (n[i]%2==0) { //function map(el => sum +=el) el = n[i]; // 2, 4, 6 sum += el; //2+4+6 } } console.log(sum); //12

+1

Do you understand Object and Array? function magic(...nums) { // the argument nums is [Object Array] in construction function let sum = 0; //sum ==0 nums.filter(n => n % 2 == 0).map(el => sum+= el); // from all elements in array any one n% 2 == 0 like 2 4 6 will be // .map el all elements still.in array will add to run finally 12 because 2 + 4 + 6 the last elements in nums here return sum; } console.log(magic(1, 2, 3, 4, 5, 6));

0

This is magic code...you'll get headeck

0

Honestly i think these arrows concerning ES6 is a mistake but...