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?

share|improve this question
4  
@TJHeuvel I don't agree, this is not the same question... Here tlaks about number of parameters and the other about default parameters – Jean-Charles Sep 9 '11 at 13:59
1  
possible duplicate of JavaScript variable number of arguments to function – Alexis King Jan 21 '15 at 5:59
up vote 24 down vote accepted

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]);
share|improve this answer
    
I also saw this solution in the book: "Javascript, the definitive guide". Thanks. – McSas Sep 13 '11 at 2:56

If an argument is not present, use the default. Like this...

function accident() {
    //Mandatory Arguments
    var driver = arguments[0];
    var condition = arguments[1]

    //Optional Arguments
    var blame_on = (arguments[2]) ? arguments[2] : "Irresponsible tree" ;
}

accident("Me","Drunk");
share|improve this answer

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);
share|improve this answer

As an add-on: You can assign values to the unnamed function parameters, as in (german wiki)

arguments[0] = 5;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.