ES6 - Rest Parameter

ES6 JavaScript

In the previous tutorials we learned about Spread Operator and how to spread array and object. In this tutorial we will learn about Rest Parameters.

We use the rest parameters ... to collect all the elements in an array.

Creating add function that takes multiple arguments and returns the sum

Let's say we want to create a function that takes two numbers and returns the sum. For this we can write the following code.

function add(x, y) {
  return x + y;

And imagine people start using our code and they like our add function. Days pass by and we get a new requirement. Now our users of the add function wants it to take two or three arguments.

We can solve this by either creating a new add3 function that takes three arguments and return the sum or we can enhance the same add function.

Introducing an a new function will implies that we have to maintain two functions. So, it is better to enhance the same function and keep things simple.

So, to achieve this we introduce a third parameter and set its default value to 0 like the following.

function add(x, y, z = 0) {
  return x + y + z;

We ship our code and people love the change. Now if they want to pass two and three arguments to the same add function and get the sum.

Now, a new requirement comes in and this time the users of our add function wants to pass 5 arguments to the add function.

So, if we go with our previous approach then our add function will start to look like the following.

function add(x, y, z = 0, a = 0, b = 0) {
  return x + y + z + a + b;

We think about the above code and realise that if we keep on introducing arguments to the same add function it will become real ugly and real fast.

This is were we take help of the rest parameters (...). So, if we want to make our add function capable of taking any number of arguments and return the sum then we can modify our code like the following.

function add(...args) {
  let sum = 0;
  for (let number in args) {
    sum += number;
  return number;

Now, we call the add function will different number of arguments.

add(1, 2);          // 3
add(1, 2, 3);      // 6
add(1, 2, 3, 4);  // 10

Using rest parameters to collect some of the arguments in an array

Let's say we have a function that can take any number of arguments. And we want to save the first and second arguments in two separate variable and rest of the arguments in a third variable.

To achieve this we can write the following code.

function foo(x, y, {

foo('hello', 'world', 1, 2, 3);

The above code will assign hello to x and world to y. 1, 2, 3 will be assigned to rest. So we will get the following output.

[ 1, 2, 3 ]