+ 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));
11 Answers
+ 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.
+ 4
You can use reduce method for rest parameters:
function Add(...args){
return args.reduce((acc, curent) => acc + curent);
};
+ 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
+ 2
It looks alright, but to be sure why not run the code yourself ??
+ 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?
+ 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));
+ 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));
0
OK ChaoticDawg and Logomonic Learning
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));
0
can anyone try and explain this in depth please
0
function myfun(...args) {
let sum = 0;
args.forEach((num) => {
sum = sum + num;
});
console.log(sum);
}
myfun(10, 20, 30, 40, 50);