JavaScript rest operator

20 October 2022

The rest operator in JavaScript is a series of 3 dots (...) and is used to put the rest of some values into an array and then assign it to the value specified after the 3 dots.

The best way to learn how to use the rest operator is to look at a few examples.

Objects and the rest operator

Let’s take one of the objects we were using in the JavaScript destructuring examples and use it with the rest operator.

let car = {
    make: 'Ferrari',
    model: 'Enzo',
    country: 'Italy',
    colour: 'Red'
}
let {make, ...others} = car;

console.log(make);
console.log(others);

Here we’re assigning the make property in the cars object to a variable called make. Then, using the rest operator, copying the rest of the properties in the object to a new object called others.

When we run this we get the following output:

Output
Ferrari
Object { model: "Enzo", country: "Italy", colour: "Red" }

One thing to note about the rest operator is that it can only be used as the last parameter so nothing else can come after it. For example we couldn’t just get the middle two properties from this object.

let car = {
    make: 'Ferrari',
    model: 'Enzo',
    country: 'Italy',
    colour: 'Red'
}
let {make, ...others, colour} = car;

Doing that would result in the following error:

Output
Uncaught SyntaxError: rest element may not have a trailing comma

Array’s and the rest operator

The rest operator in an array works in a very similar way to how it does with an object. The difference is, instead of copying the rest of the values into an object it copies them into an array.

Here’s the same data this time in an array being destructured with the rest operator.

let car = ['Ferrari', 'Enzo', 'Italy', 'Red'];
let [make, ...others] = car;

console.log(make);
console.log(others);
Output
Ferrari
Array [ "Enzo", "Italy", "Red" ]

Functions and the rest operator

Finally, we can use the rest operator in a function at the end of the arguments list to group the rest of the arguments into an object.

In the following function we define the first two arguments as make and model, but then any other arguments that follow are added into the others object.

function cars(make, model, ...others) {
    return others;
}

cars('Ferrari', 'Enzo', 'Italy', 'Red');

The rest operator is useful for collecting multiple arguments into one object, especially when you don’t know how many objects there will be or this number will vary.