Pass unknown number of arguments into JavaScript function

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]);
}

Leave a Comment