In Chrome, when I type console.log in the one below:
console.log("A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter");
…it prints it correctly, with no errors or warnings. I appended more parameters, but it still prints it out correctly.
console.log("A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter");
How can I have an “infinite” parameter function just like that one?
Functions can access an array-like object called
argumentsthat contains all the arguments that they receivedAnd you can do the opposite conversion (call a function given a list of arguments) with the apply method:
Some important points to note:
argumentsisn’t an actual array and it has none of the usual array methods (slice, join, etc). You can convert it to an array with the following line:Slice is also useful if you want your array to only contain the non-named arguments that were received:
Not every browser can handle an arbitrarily large number of function parameters. Last time I tested this, in Chrome and IE there was a stackoverflow after some 200.000 arguments. If your function can receive an arbitrarily large number of arguments, consider packing all of those arguments in an regular array instead.
Those
/**/comments that appear in the arguments lists for my examples are not mandatory. They are just a coding a convention that I use to mark my variadic functions and differentiate them from regular functions.