24

A pattern in some javascript libraries is to be able to pass any number of parameters to a function:

functiona(param1)
functiona(param1, param2, param3)
functiona(param1, param2)

I have an array of unknown length, and I'd like to pass all the array items as parameters to a function like functiona(). Is this possible? If so, what is the syntax for doing this?

Alex
  • 1,453
  • 12
  • 21
  • 2
    It is not a duplicate of [What is the difference between call and apply](http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply)! – ericbn Jun 07 '15 at 15:24
  • Yeah, I agree. This question isn't a duplicate, and while the other question does provide the answer, that answer is a small part of a larger discussion. – Alex Jun 09 '15 at 00:18

3 Answers3

17

What you want is probably Function.prototype.apply().

Usage:

var params = [param1, param2, param3];
functiona.apply(this, params);

As others noted, functiona declaration may use arguments, e.g.:

function functiona()
{
    var param1 = this.arguments[0];
    var param2 = this.arguments[1];
}

But it can use any number of normal parameters as well:

function foo(x, y)
{
    console.log(x);
}
foo.apply(this, [10, 0, null]); // outputs 10
zlumer
  • 6,088
  • 1
  • 19
  • 23
4

Use arguments:

The arguments object is an Array-like object corresponding to the arguments passed to a function.

CD..
  • 65,131
  • 24
  • 138
  • 151
3

Yep, all parameters passed to a JavaScript function can be accessed using the arguments array within the function.

function foo () {
    console.log(arguments[0]); // -> bar
    console.log(arguments[1]); // -> baz
}

foo('bar', 'baz');
iota
  • 34,586
  • 7
  • 32
  • 51
Kevin Nagurski
  • 1,869
  • 9
  • 23