https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-the-rest-parameter-with-function-parameters
const sum = (…args) => {
return args.reduce((a, b) => a + b, 0);
}
My only doubt is why do we add the ‘0’ at the end
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-the-rest-parameter-with-function-parameters
const sum = (…args) => {
return args.reduce((a, b) => a + b, 0);
}
My only doubt is why do we add the ‘0’ at the end
It’s initial value, think about the below. Go to the MDN maybe, there are bunch of examples.
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}
console.log(sum(2,3));//5
const sum1 = (...args) => {
return args.reduce((a, b) => a + b, 1);
}
console.log(sum1(2,3));//6
Ok thanks
Got it!
NOTE: You do not need to add the 0
to accomplish this particular task. If an initial value is not specified, the first value of the acc is the first element of the array.
But this task requires 0 to solve it.
?
Yup, I believe that’s because of the testcase: sum()
const sum = (...args) => {
return args.reduce((a, b) => a + b);
}
console.log(sum());
/*
TypeError: Reduce of empty array with no initial value
at Array.reduce (<anonymous>)
.......
*/
@Scharnhorst89 @admit8490 You can still use reduce
with an initial value of 0
if the function is written to handle the case of no arguments passed to the function.