JavaScript rest operator | Rest parameter

  • by

The rest operator (Rest parameter ) instructs the computer to add whatever arguments) supplied by the user into an array. The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.

Triple dots… is the rest parameter. Rest syntax looks exactly like spread syntax.

function functionname(...parameters)  
{
   statement;
}

JavaScript rest operator

A simple example code calls a function with any number of arguments and then accesses those excess arguments as an array.

<!DOCTYPE html>
<html>
<body>

<script>
   function addAll(...num){
    let sum = 0;
    for(let i of num){
      sum+=i;
    }
    return sum;
  }
  console.log(addAll(1,2)); 
  console.log(addAll(1,2,3)); 
  console.log(addAll(1,2,3,4,5)); 

</script>

</body>
</html> 

Output:

JavaScript rest operator

Use rest to enclose the rest of specific user-supplied values into an array:

<script>
   function myBio(firstName, lastName, ...otherInfo) { 
    return otherInfo;
  }

  var res = myBio("John", "wick", "is a", "Web Developer", "in EyeHunts");
  console.log(res)

</script>

Output: [ “is a”, “Web Developer”, “in EyeHunts” ]

Do comment if you have any doubts or suggestions on this JS Rest topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.