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:

Javascript code for display parameter using rest operator

<script> 

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

</script>

Output

Hello
1,2,3,4,5

Javascript code demonstrating addition of numbers using rest operator.

<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>					 

Output

15

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

  • JavaScript
  • Rest Operator