+ 4

ES6 60.2 summary calculator

Hello, I am a newbie to coding I managed to solve this but I was wondering what a better syntax could be? thank you in advance! //complete the function function Add(...nums){ let sum=0 for (let i=0; i<=nums.length-1; i++){ sum = sum + nums[i]; } return sum; } console.log(Add(1,2,3)); console.log(Add(4,14,5,9,14)); console.log(Add(2,36));

17th Jul 2021, 2:01 PM
Xheni Lamaj
Xheni Lamaj - avatar
3 odpowiedzi
+ 2
Not sure about better syntax but there is a reduce method that you can use to make the code short! Add=(...nums)=>{ return nums.reduce((a,b)=>a+b) }
17th Jul 2021, 2:33 PM
Abhay
Abhay - avatar
+ 1
function Add(...numbers){ let sum = 0 for ( let number of numbers){ sum += number } return sum; }
6th Nov 2022, 9:05 PM
Khouloud Mekni
Khouloud Mekni - avatar
+ 1
i do it again by the foreach method function Add(...numbers){ let sum=0 numbers.forEach(number=>{sum += number}) return sum; }
6th Nov 2022, 9:17 PM
Khouloud Mekni
Khouloud Mekni - avatar