Arbitrary Parameters with the arguments Object

In last week's issue we discussed default parameters. That gives us some flexibility when working with parameters, but what if we want something that would accept as many arguments as we can throw at it? Say for example that we want to create a function which adds together all the arguments we pass to it. How would we go about that?

functionaddAll(){// What do we do here?}// Should return 6addAll(1,2,3);// Should return 10addAll(1,2,3,4);

Fortunately, JavaScript does have an answer, though it is a little quirky. The answer is the arguments object.

Though it isn't exactly an array, the arguments object acts like an array that happens to contain every parameter passed to the function.

This can easily bite you, especially if you pass the contents of arguments to another function which expects a real array.

The solution is surprisingly easy to use, but a little more difficult to understand.

functionsortArgs(){// Convert arguments object into a real arrayvarargs=[].slice.call(arguments);// Now this will work!sorted=args.sort()returnsorted;}

What's going on here has several steps:

We create an empty array.

We use the array's slice method.

We use the call method to tell slice that it should operate on arguments rather than on the empty array.

Invoking slice without specifying which index the slice should begin at will return an unsliced array. And that's how we end up with exactly what we want: a real array that contains every parameter that was passed to the function.

Want to improve your JavaScript skills?
Subscribe to A Drip of JavaScript for biweekly tips to help you level up as a JS developer.