Core JavaScript

Variable Arguments Versus Rest Parameters

This JavaScript example illustrates the difference between variable arguments and rest parameters. One of the key differences is that arguments variable of the type Arguments while the rest parameters are passed in as an Array object.

FunctionsVarArgVersusRestParams.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="FunctionsVarArgVersusRestParams.js"></script>
</body>
</html>

FunctionsVarArgVersusRestParams.js

// An extra function to display the type of variable
function GetTypeName(x) {
    return {}.toString.call(x).slice(8, -1);
}

// Variable Arguments
function PrintArgs() {
	document.writeln("Inside PrintArgs()<br />");
	document.writeln("------------------<br />");
	for (sProp in arguments) {
		document.writeln(sProp + " : " + arguments[sProp] + "<br />");
	}
	// arguments is of Arguments type
	document.writeln("The type is " + GetTypeName(arguments) + "<br />");
	// To get an array, convert arguments
	qaArguments = Array.from(arguments);
	document.writeln("The type is " + GetTypeName(qaArguments) + "<br />");
	document.writeln("<br />");
}

// Rest Parameters
function PrintParams(...xRestParams) {
	document.writeln("Inside PrintParams()<br />");
	document.writeln("--------------------<br />");
	for (sProp in xRestParams) {
		document.writeln(sProp + " : " + xRestParams[sProp] + "<br />");
	}
	// xRestParams is of Array type
	document.writeln("The type is " + GetTypeName(xRestParams) + "<br />");
	document.writeln("<br />");
}

PrintArgs("XoaX.net", 99, 8.22, 't');

PrintParams("XoaX.net", 99, 8.22, 't');
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.