+ 1

Can anyone check if my code is correct?

I am using rest operator to calculate sum, am not sure if this code is correct //complete the function function Add(...nums){ let sum = 0; for (let i of nums) { sum += i; } return sum; } console.log(Add(1,2,3)); console.log(Add(4,14,5,9,14)); console.log(Add(2,36));

20th Dec 2020, 11:57 PM
Krishneel Sharma
Krishneel Sharma - avatar
11 ответов
+ 5
FYI, ... is the spread operator, and when used to get the "rest" of the passed arguments to a function or method, like you are using, along with a parameter name, it is called the "rest parameter". ...but yes, your code is fine. You could simply have run your code and determined that it is working correctly without errors to know this though.
21st Dec 2020, 12:37 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
You can use reduce method for rest parameters: function Add(...args){ return args.reduce((acc, curent) => acc + curent); };
1st Sep 2021, 2:18 PM
Алексей Саблин
Алексей Саблин - avatar
+ 4
//complete the function function Add(...args){ return args.reduce((acc, curent) => acc + curent); }; console.log(Add(1,2,3)); console.log(Add(4,14,5,9,14)); console.log(Add(2,36)); Good Luck
25th Jan 2022, 8:52 AM
Muhammad Alif Deva Rizqon
Muhammad Alif Deva Rizqon - avatar
+ 2
It looks alright, but to be sure why not run the code yourself ??
21st Dec 2020, 12:33 AM
Logomonic Learning
Logomonic Learning - avatar
+ 1
function Add(...nums){ let sum=0; for(let num of nums){ sum+=num; } return sum; } function Add(){ } console.log(Add(1,2,3)); console.log(Add(4,14,5,9,14)); console.log(Add(2,36)); // Is is right?
25th Aug 2022, 4:25 PM
NURUL AMIN
NURUL AMIN - avatar
+ 1
this is how I did it //complete the function function Add(a,b, ...c){ let result = a + b; c.forEach(function(number){ result += number }); return result; } console.log(Add(1,2,3)); console.log(Add(4,14,5,9,14)); console.log(Add(2,36));
29th Sep 2022, 2:10 AM
Andres Moran Cabello
Andres Moran Cabello - avatar
+ 1
function Add(...args){ return args.reduce((acc, curent) => acc + curent); }; console.log(Add(1,2,3)); console.log(Add(4,14,5,9,14)); console.log(Add(2,36));
14th Nov 2022, 10:45 AM
Daniela Bulimar
Daniela Bulimar - avatar
21st Dec 2020, 1:04 AM
Krishneel Sharma
Krishneel Sharma - avatar
0
function Add(...nums){ let sum = 0; for (let i of nums) { sum = sum + i; } return sum; } console.log(Add(1,2,3)); console.log(Add(4,14,5,9,14)); console.log(Add(2,36));
20th Sep 2022, 1:42 PM
Alexander OKUNRINKOYA
0
can anyone try and explain this in depth please
11th Jan 2023, 6:32 PM
Phillipe John Jules
Phillipe John Jules - avatar
0
function myfun(...args) { let sum = 0; args.forEach((num) => { sum = sum + num; }); console.log(sum); } myfun(10, 20, 30, 40, 50);
23rd Nov 2023, 6:51 PM
Shoaib Ahmad
Shoaib Ahmad - avatar