Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript variable number of arguments to function

Is there a way to allow "unlimited" vars for a function in JavaScript?

Example:

load(var1, var2, var3, var4, var5, etc...) load(var1) 
like image 342
Timo Avatar asked Jan 26 '10 18:01

Timo


People also ask

Can we pass a variable number of arguments to a function JavaScript?

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.

Does JavaScript support variable number of arguments to functions or methods?

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.

How can you get the total number of arguments passed to a function in JavaScript?

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 ).

Does JavaScript functions check for the number of arguments received?

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.


2 Answers

Sure, just use the arguments object.

function foo() {   for (var i = 0; i < arguments.length; i++) {     console.log(arguments[i]);   } } 
like image 171
roufamatic Avatar answered Nov 08 '22 14:11

roufamatic


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

like image 45
Ramast Avatar answered Nov 08 '22 13:11

Ramast