Pass unknown number of arguments into JavaScript function

Is there a way to pass an unknown number of arguments like:

var print_names = function(names) {
    foreach(name in names) console.log(name); // something like this
}

print_names('foo', 'bar', 'baz');

Also, how do I get the number of arguments passed in?


ES3 (or ES5 or oldschool JavaScript)

You can access the arguments passed to any JavaScript function via the magic arguments object, which behaves similarly to an array. Using arguments your function would look like:

var print_names = function() {
     for (var i=0; i<arguments.length; i++) console.log(arguments[i]);
}

It's important to note that arguments is not an array. MDC has some good documentation on it: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object

If you want to turn arguments into an array so that you can do things like .slice(), .push() etc, use something like this:

var args = Array.prototype.slice.call(arguments);

ES6 / Typescript

There's a better way! The new rest parameters feature has your back:

var print_names = function(...names) {
    for (let i=0; i<names.length; i++) console.log(names[i]);
}

ES6/ES2015

Take advantage of the rest parameter syntax.

function printNames(...names) {
  console.log(`number of arguments: ${names.length}`);
  for (var name of names) {
    console.log(name);
  }
}

printNames('foo', 'bar', 'baz');

There are three main differences between rest parameters and the arguments object:

  • rest parameters are only the ones that haven't been given a separate name, while the arguments object contains all arguments passed to the function;
  • the arguments object is not a real array, while rest parameters are Array instances, meaning methods like sort, map, forEach or pop can be applied on it directly;
  • the arguments object has additional functionality specific to itself (like the callee property).

var 
print_names = function() {
    console.log.apply( this, arguments );
};

print_names( 1, 2, 3, 4 );

function print_args() {
    for(var i=0; i<arguments.length; i++)
        console.log(arguments[i])
}

There is a hidden object passed to every function in JavaScript called arguments.

You would just use arguments.length to get the amount of arguments passed to the function.

To iterate through the arguments, you would use a loop:

for(var i = arguments.length; i--) {
   var arg = arguments[i];
}

Note that arguments isn't a real array, so if you needed it as an array you would convert it like this:

var args = Array.prototype.slice.call(arguments);