can you expain this code ? I can't able to understand ! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

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 ?

12th Jun 2019, 1:52 PM
Injamul Mohammad Mollah
Injamul Mohammad Mollah - avatar
4 Answers
+ 23
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
18th Aug 2019, 12:32 AM
Al-Amin Rais
Al-Amin Rais - avatar
+ 8
this is a simple one{ step 1 = filter() returns all the numbers that pass the test, step 2 = the percentage sign means the remainder of a number divided by a number in this case n divided by 2: , step 3 = from the filter() the number that pass the test are 2,4, and 6;, step 4 = the Map() returns what the function wants it to do, in this test its to sum all the numbers; last step = 2 + 4 + 6 which you get 12😀, } hope this helped you. please correct me where I am wrong if that the case😎
23rd Sep 2020, 11:51 AM
Jack Murimi Kavita
Jack Murimi Kavita - avatar
+ 2
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));
12th Jun 2019, 2:14 PM
Basel.Al_hajeri?.MBH()
Basel.Al_hajeri?.MBH() - avatar
+ 2
What I don't understand is as to why the authors decided to test us on something that we haven't covered yet like the filter method and map instead of making simple for us to at least get the idea of what's being taught they make it even more difficult by introducing subjects that they haven't covered yet! Pointless.
21st Nov 2020, 2:45 PM
Eduardo J Cerejo
Eduardo J Cerejo - avatar