Passing an array as a function parameter in JavaScript

Robert picture Robert · May 18, 2010 · Viewed 548.1k times · Source

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()?

Answer

KaptajnKold picture KaptajnKold · May 18, 2010
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:

call_me(...args);