Close

JavaScript - Rest Parameters

[Updated: Sep 23, 2018, Created: Jul 16, 2018]

ES9 (ECMAScript 2018) introduced the following new syntax to declare a number of function parameters as a single variable of array type:

function myFunction( ...myArgs ){ }

Example

function print(...args) {
    console.log(args.length);
    console.log(args);
    for (let i = 0; i < args.length; i++) {
        console.log(args[i]);
    }
}
print(5, 'test', new Date());
function print(num, ...args) {
    console.log(num);
    console.log(args);
    for (let i = 0; i < args.length; i++) {
        console.log(args[i]);
    }
}
print(5, 'test', new Date());

Rest parameters can only be used at the end.

function print(...args, num) {
    console.log(num);
    console.log(args);
    for (let i = 0; i < args.length; i++) {
        console.log(args[i]);
    }
}
print(5, 'test', new Date());

See Also