I'm writing a sum(...numbers) function which takes in a bunch of arguments via the Spread operator and adds them. I want to pass an array of values to this function via the returnsAnArray() method, as shown below
function sum(...numbers) { let sum = 0; for (i = 0; i < numbers.length; i++) { sum += numbers[i]; } return sum; } function returnsAnArray() { return [1,2,3,4]; } console.log(sum(returnsAnArray())); This outputs 01,2,3,4 on the console.
From what I understand the ... operator collects all the arguments passed to it and makes them available as an array. If the argument is a singular array then it the array is provided as is. But this does not behave that way.
Any ideas on how I can properly use loops here to get this working as expected?
...numbersin the functionsummeans, there is no defined number of arguments, instead accept as many as passed. Now you are calling the function sum with a single argument of type array, so this is interpreted as the first parameter to the function sum to be of type array and not what you expect/intend. Hope the answer below helps