Having a complete and utter brain fart here
Why are we doing sum = sum + numbers[i].
I've even looked at the result if we do sum = numbers[i] or sum = sum + numbers and for the life of me can't figure it out.
Any help would be appreciated
const add = function (...numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) sum += numbers[i];
console.log(sum);
};
add(2, 3);
add(5, 3, 7, 2);
add(8, 2, 5, 3, 2, 1, 4);
Have a look at the MDN docs for Rest parameters
That essentially means that rest parameters are just some syntactic sugar and equivalent to the following:
With
numbers[i]
you get the value at thei
-th position in the array andsum += numbers[i]
is short forsum = sum + numbers[i]
, meaning thatadd()
will sum up all the values (from index0
to indexnumbers.length - 1
) in the array and the total value will be logged to the console.