JavaScript | Rest Operator

Rest Operator is an improved way to handle function parameter, allowing us to more easily handle various input as parameters in a function.
JavaScript has allowed a variable number of function parameters of a function but the problem is that it is not an array. It is an array like object. Therefore performing some operations on “arguments” will give an error.
Rest operator is added in ES2015 or ES6 which improved the ability to handle parameter.
Syntax:

function functionname[...parameters]//... is the rest operator
{
statement;
}

It stores n number of parameters as an array.

JavaScript code to show the working of Rest Operator:

Code #1:
Javascript code for display parameter using rest operator

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
   // Calling of function
   function onlyMath(operator, ...numbers) {
   document.write(operator +"<br>");
   document.write(numbers);
   }
   onlyMath('Hello',1,2,3,4,5);
  
</script>                    

chevron_right


Output

Hello
1,2,3,4,5

Code #2:
Javascript code demonstrating addition of numbers using rest operator.

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
   //function passed with parameters using rest operator.
   function total(...args) {
   var result = 0;
     
   //args is used as a variable to add numbers.
   for(var i = 0; i < args.length; i++) {
    result += args[i];
   }
   return result;
     
   //scope of args ends here.
   }
   document.write(total(1, 6, 8));
     
</script>                    

chevron_right


Output

15

The operation can be performed on the args variable but the scope is only under brackets.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.