Rest Parameter and Spread Syntax in JavaScript

Before we move on to the more advanced topics regarding functions, we need to take another look at the function arguments. We demonstrated before that a function could accept a single input argument:

javascript
1function example(str) {
2  console.log(str);
3}

Multiple arguments:

javascript
1function example(str1, str2) {
2  console.log(str1 + " " + str2);
3}

Arguments with default values:

javascript
1function example(a, b = 0) {
2  return a ** b;
3}

Or no argument at all:

javascript
1function example() {
2  console.log("123");
3}

Rest parameter

Now, let's consider a more challenging scenario. What if you need a function that calculates the sum of an indefinite number of arguments? It could be 10, 100, or even 1000. Creating a function that accepts 1000 arguments is obviously impractical, so instead, you could define a rest parameter.

javascript
1function sumAll(...nums) {
2  let sum = 0;
3  for (let num of nums) {
4    sum += num;
5  }
6  return sum;
7}
8
9console.log(sumAll(1, 2, 3, 4));

A rest parameter is defined by placing ... before the parameter name. Values passed to that parameter will be saved in an array. You can then access individual elements inside that array using the for of loop we discussed before.

A rest parameter can work alongside regular parameters, but it must be placed at the end. For example, the following example will not work:

javascript
1function sumAll(a, ...nums, b) {
2  . . .
3}

The rest parameter will collect all remaining values passed to the function, hence the name, "rest" parameter.

The spread syntax

In some cases, you'll need to do the opposite. For instance, the built-in method Math.max() returns the greatest number from a list of values.

javascript
1let maxNumber = Math.max(5, 10, 15, 3);
2
3console.log(maxNumber); // -> 15

But if you are given an array of numbers, simply passing the array to the method is not going to work. You need to convert the array into a list of variables. Of course, you can do things the hard way and pass the array elements individually.

But when you have an array of 100 elements or more, that is not going to be practical. Instead, you should use the spread syntax.

javascript
1let numbers = [5, 10, 15, 3, 9, 16, 81, 32];
2let maxNumber = Math.max(...numbers);
3
4console.log(maxNumber); // -> 81

Notice that the spread syntax looks exactly like the rest parameter, by adding three dots (...) in front of the variable name, but it works the opposite. The spread syntax will convert an array into a list of variables so that the method Math.max() can work with them.