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:


Anyone knows how to define this function?

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

myFunction(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]);

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({

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

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

Use the ‘arguments’ variable like this :

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

Call the methods as you did before


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


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

arguments[0] = 5;

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Zoomable, Google-Finance-style time series graph in D3 or Rickshaw? [closed]

Similar Posts