To create a function which accepts an undetermined number of arguments, there are two methods depending on your environment.
Whenever a function is called, it has an Array-like arguments object in its scope, containing all the arguments passed to the function. Indexing into or iterating over this will give access to the arguments, for example
function logSomeThings() {
for (var i = 0; i < arguments.length; ++i) {
console.log(arguments[i]);
}
}
logSomeThings('hello', 'world');
// logs "hello"
// logs "world"
Note that you can convert arguments
to an actual Array if need-be; see: Converting Array-like Objects to Arrays
From ES6, the function can be declared with it's last parameter using the rest operator (...
). This creates an Array which holds the arguments from that point onwards
function personLogsSomeThings(person, ...msg) {
msg.forEach(arg => {
console.log(person, 'says', arg);
});
}
personLogsSomeThings('John', 'hello', 'world');
// logs "John says hello"
// logs "John says world"
Functions can also be called with similar way, the spread syntax
const logArguments = (...args) => console.log(args)
const list = [1, 2, 3]
logArguments('a', 'b', 'c', ...list)
// output: Array [ "a", "b", "c", 1, 2, 3 ]
This syntax can be use to insert arbitrary number of arguments to any position, and can be used with any iterable(apply
accepts only array-like objects).
const logArguments = (...args) => console.log(args)
function* generateNumbers() {
yield 6
yield 5
yield 4
}
logArguments('a', ...generateNumbers(), ...'pqr', 'b')
// output: Array [ "a", 6, 5, 4, "p", "q", "r", "b" ]