Skip to content
Related Articles

Related Articles

Explain the Rest parameter in ES6

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 12 Jan, 2022

In this article, we will try to understand the details associated with the rest parameter in ES6 which includes syntax of rest parameters, how to use this with the help of certain examples.

Let us first understand the basic details which are associated with the Rest parameter.

function display(first_argument,...other arguments) {
  console.log(other arguments);


Rest Parameter:

  • Rest parameter allows us to handle more number of inputs which is getting passed inside a function in a much effective and easier manner.
  • The rest parameter allows us to treat an indefinite amount of values as the values of an array, which means the values which are passed using the rest parameter syntax are treated as array elements or array values.
  • Using rest parameters in our code makes our code more readable and more cleaner.

Syntax: Following is the syntax of using rest parameter in our code-

function function_name (...arguments) {
    // Code logic.........

By using the above-illustrated syntax, we may easily pass on several arguments in one function which further helps any user to make the code more readable and cleaner.

Now after understanding the basic details regarding the rest parameter, let us look at some examples to see how we could effectively use this rest operator.

Example 1: In this example, we will use a simple way of writing function further adding rest parameters and passing on some arguments inside a function as parameters while calling the function itself.


    function display(first_argument, ...other_arguments) {
    display(1, 2, 3, 4, 5, 6);

Output: The output of the above snippet is as follows-

[ 2, 3, 4, 5, 6 ]

Example 2: In this example, we will calculate the sum of all the numbers which are passed by the user inside the function as parameters while calling.


    function sum(...numbers) {
        let sum = 0;
        for (let element of numbers) {
            sum += element;
    sum(1, 5, 5, 3, 6);
    sum(1, 2, 3, 4);
    sum(0, 1, 2);

Output: The output of the above code snippet is shown below-


Example 3: In this example, we will sort all the arguments which are provided by the user at the time of the function call.


    function sortNumbers(...numbers) {
        let sortedResult = numbers.sort();
        return sortedResult;
    console.log(sortNumbers(1, 2, 3, 4, 0));
    console.log(sortNumbers(5, 2, 9, 7));

Output: The output of the above code snippet is shown below-

[ 0, 1, 2, 3, 4 ]
[ 2, 5, 7, 9 ]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!