DEV Community

Rajat Gupta
Rajat Gupta

Posted on

rest parameter in javascript

The rest parameter is introduced in ES6. It allows a function to accept an indefinite number of arguments as an array that is we can call a function with as many arguments as we want and the rest parameter will gather all these arguments into an array.

See the below example to understand how:

Example 1:

function testing(...numbers){
       console.log(numbers)
       console.log(numbers[0])
       console.log(numbers[2])
}

testing(2, 16, 7, 4)

//Result 1: [2, 16, 7, 4]
//Result 2: 2
//Result 3: 7
Enter fullscreen mode Exit fullscreen mode

The syntax of the rest parameter is just 3 dots followed by the array name. In the above ☝️ example, we do not have to know how many arguments are there in order to define parameters. Rather, we can simply use the rest parameter. Using the rest parameter we can tackle an infinite number of arguments.

Let's see some more examples:

Example 2:

function testing(a, ...numbers){
       console.log(a)
       console.log(numbers)
}

testing(2, 16, 7, 4)

//Result 1: 2 
//Result 2: [16, 7, 4]
Enter fullscreen mode Exit fullscreen mode

In the above example, we can see that the parameter "a" is assigned with 2, and the rest of the arguments are stored in the numbers array.

NOTE: The rest parameter must always be the last parameter. The below code will result in an error.
Example 3:

function testing(a, ...numbers, b){
       console.log(a)
       console.log(numbers)
       console.log(b)
}

testing(2, 16, 7, 4)

//Error: Uncaught SyntaxError: Rest parameter must be last formal parameter
Enter fullscreen mode Exit fullscreen mode

Example 4: Write a function to sum all the arguments provided? Number of arguments are not known.

function sumAll(...args) {
  let sum = 0;

  for (let arg of args){
        sum += arg;
    }

  return sum;
}

console.log( sumAll(1) ); 
console.log( sumAll(1, 2) ); 
console.log( sumAll(1, 2, 3) ); 

//Result 1: 1
//Result 2: 3
//Result 3: 6
Enter fullscreen mode Exit fullscreen mode

That's all folks. I'll teach spread syntax and destructuring tomorrow.

If you have any doubt ask me in the comments section and I'll try to answer as soon as possible.

I write one article every day related to web development (yes, every single f*cking day). Follow me here if you are learning the same..

If you love the article follow me on Twitter: @therajatg

If you are the Linkedin type, let's connect: https://www.linkedin.com/in/therajatg/

Have an awesome day ahead 😀!

Top comments (0)