Is there a way to allow "unlimited" vars for a function in JavaScript?
Example:
load(var1, var2, var3, var4, var5, etc...) load(var1)
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.
possible duplicate of Is it possible to send a variable number of arguments to a JavaScript function? related / possible duplicate of stackoverflow.com/questions/4633125/… @Luke no, it's not.
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 ).
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.
Sure, just use the arguments
object.
function foo() { for (var i = 0; i < arguments.length; i++) { console.log(arguments[i]); } }
In (most) recent browsers, you can accept variable number of arguments with this syntax:
function my_log(...args) { // args is an Array console.log(args); // You can pass this array as parameters to another function console.log(...args); }
Here's a small example:
function foo(x, ...args) { console.log(x, args, ...args, arguments); } foo('a', 'b', 'c', z='d') => a Array(3) [ "b", "c", "d" ] b c d Arguments 0: "a" 1: "b" 2: "c" 3: "d" length: 4
Documentation and more examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
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