Skip to content
Advertisement

Unlimited arguments in a JavaScript function

Can a JavaScript function take unlimited arguments? Something like this:

JavaScript

I am trying:

JavaScript

But this doesn’t work (output is only the first argument). Or the only way is:

JavaScript

Thanks

Advertisement

Answer

There’s a weird “magic” variable you can reference called “arguments”:

JavaScript

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:

JavaScript

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

JavaScript

More about arguments and optimization.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement