Passing an array as a function parameter in JavaScript

Passing an array as a function parameter in JavaScript

I’d like to call a function using an array as parameters:
const x = [‘p0’, ‘p1’, ‘p2’];
call_me(x[0], x[1], x[2]); // I don’t like it

function call_me (param0, param1, param2 ) {
// …

Is there a better way of passing the contents of x into call_me()?


Solution 1:

const args = ['p0', 'p1', 'p2'];
call_me.apply(this, args);

See MDN docs for Function.prototype.apply().

If the environment supports ECMAScript 6, you can use a spread argument instead:


Solution 2:

Why don’t you pass the entire array and process it as needed inside the function?

var x = [ 'p0', 'p1', 'p2' ]; 

function call_me(params) {
  for (i=0; i<params.length; i++) {

Solution 3:

Assuming that call_me is a global function, so you don’t expect this to be set.

var x = ['p0', 'p1', 'p2'];
call_me.apply(null, x);

Solution 4:

In ES6 standard there is a new spread operator ... which does exactly that.


It is supported by all major browsers except for IE.

Related:  JSDoc: Return object structure

The spread operator can do many other useful things, and the linked documentation does a really good job at showing that.

Solution 5:

As @KaptajnKold had answered

var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);

And you don’t need to define every parameters for call_me function either.
You can just use arguments

function call_me () {
    // arguments is a array consisting of params.
    // arguments[0] == 'p0',
    // arguments[1] == 'p1',
    // arguments[2] == 'p2'

Solution 6:

Note this

function FollowMouse() {
    for(var i=0; i< arguments.length; i++) {
        arguments[i] = event.clientY+"px";
        arguments[i].style.left = event.clientX+"px";



html page

<body onmousemove="FollowMouse(d1,d2,d3)">

<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>


can call function with any Args

<body onmousemove="FollowMouse(d1,d2)">


<body onmousemove="FollowMouse(d1)">