Is there a way to pass an unknown number of arguments like:
var print_names = function(names) {
foreach(name in names) console.log(name); // something like this
}
print_names('foo', 'bar', 'baz');
Also, how do I get the number of arguments passed in?
length property provides the number of arguments actually passed to a function. This can be more or less than the defined parameter's count (see Function. length ).
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit. In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.
Parameter Rules JavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received.
Unless otherwise specified in the description of a particular function, if a function or constructor described in this clause is given more arguments than the function is specified to allow, the extra arguments are evaluated by the call and then ignored by the function.
You can access the arguments passed to any JavaScript function via the magic arguments
object, which behaves similarly to an array. Using arguments
your function would look like:
var print_names = function() {
for (var i=0; i<arguments.length; i++) console.log(arguments[i]);
}
It's important to note that arguments
is not an array. MDC has some good documentation on it: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object
If you want to turn arguments
into an array so that you can do things like .slice()
, .push()
etc, use something like this:
var args = Array.prototype.slice.call(arguments);
There's a better way! The new rest parameters feature has your back:
var print_names = function(...names) {
for (let i=0; i<names.length; i++) console.log(names[i]);
}
Take advantage of the rest parameter syntax.
function printNames(...names) {
console.log(`number of arguments: ${names.length}`);
for (var name of names) {
console.log(name);
}
}
printNames('foo', 'bar', 'baz');
There are three main differences between rest parameters and the arguments object:
var
print_names = function() {
console.log.apply( this, arguments );
};
print_names( 1, 2, 3, 4 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With