JavaScript – Function with Rest Parameter

Function with Rest parameter: The rest parameter(…) allows a function to collect any number of arguments.

Before rest feature (we use method overloading:

Overloading: Defining multiple functions with same name but with different arguments (parameters)

function add(x, y){
}
function add(x, y, z){
}
function add(x, y, z, w){
}

With rest feature, we can simply define as:

function add(...args){ 

}

Passing different length of arguments to function using rest parameter:

<!doctype html>
<html>
	<body>
		<script>
			function display(...args)
			{
				document.write("Input values are : <br/>");
				for(var x of args)
				{
					document.write(x + "<br/>");
				}
			}

			display(10,20);
			display(10,20,30,40,50);
			display("abc", "xyz", "lmn");
		</script>
	</body>
</html>

Adding different length of numbers using rest parameter:

<!doctype html>
<html>
	<body>
		<script>
			function add(...args)
			{
				var sum=0;
				for(var x of args)
				{
					sum=sum+x;
				}
				document.write("Sum is : " + sum + "<br/>");
			}

			add(10,20);
			add(10,20,30,40,50);
			add(10,20,30);
		</script>
	</body>
</html>
Scroll to Top