infinite arguments problem javascript code example
Example: javascript infinite parameters
Functions can access an array-like object called arguments that contains all the arguments that they received
function print_my_arguments(){
var args = arguments;
for(var i=0; i<args.length; i++){
console.log(args[i]);
}
};
Some important points to note:
- arguments isn't an actual array. You can convert it to an array with the following line:
var args = Array.prototype.slice.call(arguments);
Slice is also useful if you want your array to only contain the non-named arguments that were received:
function foo(first_arg, second_arg ){
var variadic_args = Array.prototype.slice.call(arguments, 2);
}
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.
function foo(){
console.log(arguments.length);
}