Call function with array of arguments
In ECMAScript 6, you can use spread syntax (...
) for that purpose. It's way simpler and easier to understand than Function.prototype.apply()
.
Code example:
const fn = function() {
console.log(arguments);
}
const args = [1,2,3];
fn(...args);
Since the introduction of ES6, you can sue the spread syntax in the function call:
const args = [1,2,3];
fn(...args);
function fn() {
console.log(arguments);
}
Before ES6, you needed to use apply
.
var args = [1,2,3];
fn.apply(null, args);
function fn() {
console.log(arguments);
}
Both will produce the equivalent function call:
fn(1,2,3);
Notice that I used null
as the first argument of the apply
example, which will set the this
keyword to the global object (window
) inside fn
or undefined
under strict mode.
Also, you should know that the arguments
object is not an array, it's an array-like object, that contains numeric indexes corresponding to the arguments that were used to call your function, a length
property that gives you the number of arguments used.
In ES6, if you want to access a variable number of arguments as an array, you can also use the rest syntax in the function parameter list:
function fn(...args) {
args.forEach(arg => console.log(arg))
}
fn(1,2,3)
Before ES6, if you wanted to make an array from your arguments
object, you commonly used the Array.prototype.slice
method.
function fn() {
var args = Array.prototype.slice.call(arguments);
console.log(args);
}
fn(1,2,3);
Edit: In response to your comment, yes, you could use the shift
method and set its returned value as the context (the this
keyword) on your function:
fn.apply(args.shift(), args);
But remember that shift
will remove the first element from the original array, and your function will be called without that first argument.
If you still need to call your function with all your other arguments, you can:
fn.apply(args[0], args);
And if you don't want to change the context, you could extract the first argument inside your function:
function fn(firstArg, ...args) {
console.log(args, firstArg);
}
fn(1, 2, 3, 4)
In ES5, that would be a little more verbose.
function fn() {
var args = Array.prototype.slice.call(arguments),
firstArg = args.shift();
console.log(args, firstArg);
}
fn(1, 2, 3, 4);