C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
Version 1: We access in the "func1" function the special arguments object. We use var to assign to the arguments.
Version 2: We create a temporary array and pass it to the "func2" function. An allocation must occur on each function call.
Result: In 2019, using an array seems to be faster in Chromium than using arguments.
JavaScript program that benchmarks arguments object
function func1() {
// Multiply 3 arguments together.
var s1 = arguments[0], s2 = arguments[1], s3 = arguments[2];
return s1 * s2 * s3;
}
function func2(array) {
// Multiply 3 array elements together.
var s1 = array[0], s2 = array[1], s3 = array[2];
return s1 * s2 * s3;
}
var x1 = performance.now();
// Version 1: uses arguments object.
for (var i = 0; i < 10000000; i++) {
func1(10, 20, 2);
}
var x2 = performance.now();
// Version 2: use array argument.
for (var i = 0; i < 10000000; i++) {
func2([10, 20, 2]);
}
var x3 = performance.now();
// Results.
console.log("TIME 1: " + (x2 - x1));
console.log("TIME 2: " + (x3 - x2));
Output
TIME 1 (2019): 24.489
TIME 2: 22.255
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.