Variadic function (with arbitrary number of arguments)

suggest change

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 its 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 used to insert an arbitrary number of arguments at any position, and it works 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" ]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents