Is it possible to send a variable number of arguments to a JavaScript function?
Update: Since ES6, you can simply use the spread syntax when calling the function:
func(...arr);
Since ES6 also if you expect to treat your arguments as an array, you can also use the spread syntax in the parameter list, for example:
function func(...args) {
args.forEach(arg => console.log(arg))
}
const values = ['a', 'b', 'c']
func(...values)
func(1, 2, 3)
And you can combine it with normal parameters, for example if you want to receive the first two arguments separately and the rest as an array:
function func(first, second, ...theRest) {
//...
}
And maybe is useful to you, that you can know how many arguments a function expects:
var test = function (one, two, three) {};
test.length == 3;
But anyway you can pass an arbitrary number of arguments...
The spread syntax is shorter and "sweeter" than apply
and if you don't need to set the this
value in the function call, this is the way to go.
Here is an apply example, which was the former way to do it:
var arr = ['a','b','c'];
function func() {
console.log(this); // 'test'
console.log(arguments.length); // 3
for(var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
};
func.apply('test', arr);
Nowadays I only recommend using apply
only if you need to pass an arbitrary number of arguments from an array and set the this
value. apply
takes is the this
value as the first arguments, which will be used on the function invocation, if we use null
in non-strict code, the this
keyword will refer to the Global object (window) inside func
, in strict mode, when explicitly using 'use strict' or in ES modules, null
will be used.
Also note that the arguments
object is not really an Array, you can convert it by:
var argsArray = Array.prototype.slice.call(arguments);
And in ES6:
const argsArray = [...arguments] // or Array.from(arguments)
But you rarely use the arguments
object directly nowadays thanks to the spread syntax.
You can actually pass as many values as you want to any javascript function. The explicitly named parameters will get the first few values, but ALL parameters will be stored in the arguments array.
To pass the arguments array in "unpacked" form, you can use apply, like so (c.f. Functional Javascript):
var otherFunc = function() {
alert(arguments.length); // Outputs: 10
}
var myFunc = function() {
alert(arguments.length); // Outputs: 10
otherFunc.apply(this, arguments);
}
myFunc(1,2,3,4,5,6,7,8,9,10);