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:
In the above example, the rest operator is used to gather all the arguments passed to the sum()
function into an array called numbers
. This makes it possible to handle an arbitrary number of arguments and calculate their sum.
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