Using the For Loop alongside Rest Parameters

46 views Asked by At

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);
1

There are 1 answers

0
Mushroomator On

Have a look at the MDN docs for Rest parameters

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript.

That essentially means that rest parameters are just some syntactic sugar and equivalent to the following:

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]);

With numbers[i] you get the value at the i-th position in the array and sum += numbers[i] is short for sum = sum + numbers[i], meaning that add() will sum up all the values (from index 0 to index numbers.length - 1) in the array and the total value will be logged to the console.