23

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?

3

6 Answers 6

34

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]);
1
  • I also saw this solution in the book: "Javascript, the definitive guide". Thanks.
    – McSas
    Sep 13, 2011 at 2:56
15

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]
3

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);
2

Just refer to the arguments array.

https://developer.mozilla.org/en/JavaScript/Reference/functions_and_function_scope/arguments

2

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");
1

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

arguments[0] = 5;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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