+ 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));
3 Antworten
+ 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)
}
+ 1
function Add(...numbers){
let sum = 0
for ( let number of numbers){
sum += number
}
return sum;
}
+ 1
i do it again by the foreach method
function Add(...numbers){
let sum=0
numbers.forEach(number=>{sum += number})
return sum;
}