Home TutorialsModern ES6 Syntax Rest Parameters

Rest Parameters

by TheScriptKiddie

Rest Parameters

Rest parameters are visually similar to, but functionally opposite of, the spread syntax. A rest parameter can be included in the parameter list of a function declaration. The goal of the parameter is to collect up the “rest” of the remaining arguments into an array. A rest parameter must be the last named parameter in the parameter list, and is prefixed with three dots (...). This is best illustrated with an example:

function sayHello(name, city) {
    console.log(`Hello ${name}, welcome to ${city}!`);
}
function greet(city, ...otherNames) {
    // otherNames is an array
    for (let i = 0; i < otherNames.length; i++) {
        sayHello(otherNames[i], city);
    }
}

// 'Birmingham' will go into the city parameter
// 'Jane', 'James', 'John', 'Joaquin', and 'Jasmine' will go into the rest parameter as an array
greet('Birmingham', 'Jane', 'James', 'John', 'Joaquin', 'Jasmine');

You may also like

Leave a Comment