Turning arguments into an array

In JavaScript, when you're dealing with functions that don't have a fixed number of arguments, there's a neat, built-in, local variable called arguments which almost is an array of all the arguments that have been passed to that function. Almost, but not quite. Luckily there's a simple way to close the gap and turn the arguments variable into something more manageable.

Here's a quick example of how arguments can be used:

function add() {
    for(var i = 0, total = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    alert(total);
}
add(1, 2, 3);    // alerts 6
add(1, 2, 3, 4); // alerts 10

This function can deal with any number of arguments and alerts the sum of them. Simple enough. As you can see, the arguments variable is available locally and seems to behave as an array: It has a length property and you can access the individual arguments with [index]. It is not an array however as we can see in the next example.

Instead of adding numbers, let's see if we can concatenate strings:

function concat() {
    alert(arguments.join(' '));
}
// error: arguments.join is not a function
concat('This', 'does', 'not', 'work'); 

The error appears because the arguments variable is not actually an array and doesn't have any built-in methods. That's too bad, because sometimes it would be very handy to apply some standard array methods to the arguments. Thankfully, somebody smart found a way to do just that:

function concat() {
    var args = [].splice.call(arguments,0);
    alert(args.join(' '));
}
concat('This', 'does', 'work'); // This does work

The trick is of course the statement [].splice.call(arguments,0) which, very smartly, takes a function pointer to the array splice method ([].splice) and uses the call method (that all functions have) to apply this method to the arguments variable with one argument: 0. In other words, it's equivalent to arguments.splice(0) (apart from the fact that that code wouldn't work). The result of this statement is a new array with all the original arguments in their original order which is stored in the local variable args.

Thanks to crisp for pointing out this method to me.

Have something to say about this post? Share your thoughts!