Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create functions with variable arguments in javascript?

I want to create a function in javascript with a variable amount of arguments. The next example is how I want to call this function:

myFunction(1,2);
myFunction(1,2,3);
myFunction(1,2,3,4);
myFunction(1,2,3,4,5);
myFunction(1,2,3,4,5,6);

Anyone knows how to define this function?

like image 555
McSas Avatar asked Sep 09 '11 13:09

McSas


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.

Can JavaScript function accept parameters?

A JavaScript function does not perform any checking on parameter values (arguments).

Can a function have multiple parameters JavaScript?

Functions can accept more than one argument. When calling a function, you're able to pass multiple arguments to the function; each argument gets stored in a separate parameter and used as a discrete variable within the function.

Which variable works as a function argument in JavaScript?

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0 .


3 Answers

You can access the arguments by their ordinal position without the need to state them in the prototype as follows:

function myFunction() {
  for (var i = 0; i < arguments.length; i++)
    alert(arguments[i]);
}

myFunction(1, 2, "three");

>>1
>>2
>>three

Or if you really are passing in a set of semantically related numbers you could use an array;

function myFunction(arr) { ... }
result = myFunction([1,2,3]);
like image 193
Alex K. Avatar answered Oct 17 '22 23:10

Alex K.


Latest update

Rest parameters are supported in all new browsers. Check here for details

The rest parameter syntax allows us to represent an indefinite number of arguments as an array, which you can pass it to other functions too.

function myFunction(...data){
  console.log(...data);
  myOtherFunction(...data);
}

myFunction(1,2,3);     //logs 1,2,3

myFunction([1,2,3]);   //logs [1,2,3]
like image 14
optimistanoop Avatar answered Oct 17 '22 23:10

optimistanoop


Use the 'arguments' variable like this :

function myFunction() {
    alert(arguments.length + ' arguments');
    for( var i = 0; i < arguments.length; i++ ) {
        alert(arguments[i]);
    }
 }

Call the methods as you did before

myFunction(1,2);
myFunction(1,2,3,4,5,6);
like image 3
Jean-Charles Avatar answered Oct 17 '22 23:10

Jean-Charles