Unlimited arguments in a JavaScript function

There's a weird "magic" variable you can reference called "arguments":

function manyArgs() {
  for (var i = 0; i < arguments.length; ++i)
    alert(arguments[i]);
}

It's like an array, but it's not an array. In fact it's so weird that you really shouldn't use it much at all. A common practice is to get the values of it into a real array:

function foo() {
  var args = Array.prototype.slice.call(arguments, 0);
  // ...

In that example, "args" would be a normal array, without any of the weirdness. There are all sorts of nasty problems with "arguments", and in ECMAScript 5 its functionality will be curtailed.

edit — though using the .slice() function sure is convenient, it turns out that passing the arguments object out of a function causes headaches for optimization, so much so that functions that do it may not get optimized at all. The simple, straightforward way to turn arguments into an array is therefore

function foo() {
  var args = [];
  for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
  // ...
}

More about arguments and optimization.


As of ECMAScript 2015 (or ES6) we also have access to rest parameters that give us a slightly cleaner way to manage arguments:

function foo(a, b, ...others) {
    console.log("a and b are ", a, b);

    for (let val of others) {
        console.log(val);
    }
}

foo(1, 2, 3, 4, 5);

At the time of this writing, this is supported by Chrome 47+, Firefox 15+, and Edge. The feature is also available via both Babel and TypeScript transpiling down to ES5.