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?

serv-inc
  • 35,772
  • 9
  • 166
  • 188
McSas
  • 2,224
  • 3
  • 27
  • 42
  • 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 09 '11 at 13:59
  • 1
    possible duplicate of [JavaScript variable number of arguments to function](http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function) – Alexis King Jan 21 '15 at 05:59
  • Possible duplicate of [Is it possible to send a variable number of arguments to a JavaScript function?](https://stackoverflow.com/questions/1959040/is-it-possible-to-send-a-variable-number-of-arguments-to-a-javascript-function) – Anderson Green Jun 20 '17 at 17:41

6 Answers6

33

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]);
Alex K.
  • 171,639
  • 30
  • 264
  • 288
14

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]
optimistanoop
  • 912
  • 1
  • 11
  • 14
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);
Jean-Charles
  • 1,690
  • 17
  • 28
2

Just refer to the arguments array.

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

Matthew Wilson
  • 3,861
  • 21
  • 14
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");
Stephan
  • 41,764
  • 65
  • 238
  • 329
1

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

arguments[0] = 5;
serv-inc
  • 35,772
  • 9
  • 166
  • 188