I am not understanding

The code is confusing

  **Your code so far**

const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36.

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

Yes, it is confusing. Is there a specific part that is confusing you?

1 Like
const sum = (...args) => { // ...args can be as many items in an array as you want.. it is dynamic. It is a placeholder value for the actual value which is  passed in when you invoke the function as can be seen in your console.log

return args.reduce((a, b) => a + b, 0); // you are looping through every item in (...args). In this case, the ...args has 3 items as can be seen in your console.log. 
The first item in the array is added to 0 making the 0 = to the first number in the array.
 On the second loop, the second number is added to the first number which replaced 0.
 The result of that addition replaces the number that replaced 0 and on the 3rd loop, the 3rd item in the array gets added to that number.
}
console.log(sum(1, 2, 3)); // sum(1, 2, 3) is telling ...args to be equal to an array of [1, 2, 3] 
if you want, you could console.log(sum(1, 2, 3, 4, 5, 6, 7, 8, 9)) and it would still work because in the console.log when you invoke sum, you are passing in the actual values for every item in the rest parameter ...args

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.