Arguments example. Here is a simple program that uses the special arguments object. We can access the length, and then access each value at an index.
Info: With arguments, we can make "varargs" or "params" methods in JavaScript. Any number of arguments can be passed.
JavaScript program that uses arguments
function printAnimals() {
"use strict";
// Access arguments (a special variable available).
for (var i = 0; i < arguments.length; i++) {
// Get each argument at an index.
console.log("ANIMAL NAME: " + arguments[i]);
}
}
// Call the function.
printAnimals("bird", "frog", "dog");
printAnimals("leopard");
Output
ANIMAL NAME: bird
ANIMAL NAME: frog
ANIMAL NAME: dog
ANIMAL NAME: leopard
Example benchmark. Let us begin with two pages. Each page does the same thing—we pass 3 arguments to a method and it returns the product of the numbers.
Page 1: We access in the "x" function the special arguments object. We use var to assign to the arguments.
Page 2: We create a temporary array and pass it to the "x" function. An allocation must occur on each function call.
JavaScript program that benchmarks arguments object
var x1 = performance.now();
var count = 0;
function x() {
// Multiply 3 arguments together.
var s1 = arguments[0], s2 = arguments[1], s3 = arguments[2];
return s1 * s2 * s3;
}
for (var v = 0; v < 10000000; v++) {
x(10, 20, 2);
}
var x2 = performance.now();
document.title = (x2 - x1);
JavaScript program that benchmarks array argument
var x1 = performance.now();
var count = 0;
function x(array) {
// Multiply 3 array elements together.
var s1 = array[0], s2 = array[1], s3 = array[2];
return s1 * s2 * s3;
}
for (var v = 0; v < 10000000; v++) {
x([10, 20, 2]);
}
var x2 = performance.now();
document.title = (x2 - x1);
Output
21.77 ms arguments
29.92 ms Array
Another warning. Arguments is hard to use optimally. In my testing, using both named parameters and arguments tends to be bad for performance.
Also: The length property on arguments can be accessed. And arguments can be passed to other methods without much trouble.
Tip: Always test in a benchmark harness (like the ones on this page) before changing or adding arguments usage.