Sub topic 5
Collecting the Rest in Patterns
This chapter assumes you already know array and object destructuring, including skipped elements and default values. Here we add one more piece to a pattern: a ...name slot that collects whatever the earlier parts of the pattern did not take.
The working model
A rest slot in a destructuring pattern works like a bucket placed at the end. The pattern first matches every named position or property. Everything left over goes into the bucket.
- In an array pattern, the rest element collects the remaining elements into a new, real array.
- In an object pattern, the rest property collects the remaining own enumerable properties into a new plain object.
Rest elements in array patterns
const [head, ...tail] = [10, 20, 30, 40];
console.log(head); // 10
console.log(tail); // [20, 30, 40]
const [only, ...none] = [1];
console.log(none); // [] (always an array, never undefined)
console.log(Array.isArray(none)); // trueThe rest variable is always an array. When nothing is left over it is an empty array, so you can call array methods on it without checking first.
A rest element can also be a pattern itself, though code that does this is rarely clearer:
const [x, ...[y, z]] = [1, 2, 3];
console.log(x, y, z); // 1 2 3Rest properties in object patterns
const response = { status: 200, headers: { type: 'json' }, body: '{}', cached: false };
const { status, body, ...meta } = response;
console.log(status); // 200
console.log(meta); // { headers: { type: 'json' }, cached: false }The object rest includes only own enumerable properties that the pattern did not name. Inherited properties from the prototype are left out. The result is a new plain object, so its prototype is Object.prototype even when the source was a class instance.
class Point {
constructor() { this.x = 1; this.y = 2; }
describe() { return `${this.x},${this.y}`; }
}
const { x: px, ...others } = new Point();
console.log(others); // { y: 2 }
console.log(typeof others.describe); // 'undefined' (methods live on the prototype)Rules the parser enforces
| Rule | Example that fails | Error |
|---|---|---|
| Rest must be the last item | `const [...a, b] = arr;` | SyntaxError |
| No trailing comma after rest | `const [a, ...b,] = arr;` | SyntaxError |
| Only one rest per pattern | `const { ...a, ...b } = obj;` | SyntaxError |
| A rest slot cannot have a default | `const [...a = []] = arr;` | SyntaxError |
| Object rest must be a plain identifier in a declaration | `const { ...{ a } } = obj;` | SyntaxError |
Common errors
- Expecting
undefinedfor an empty remainder. Array rest gives[], and object rest gives{}. - Trying to collect the start of an array. Rest only works at the end. To get everything except the last item, use
arr.slice(0, -1). - Expecting methods to survive object rest. Prototype methods are not own properties, so the collected object will not have them.
Exercise
What do rest and tail contain after this code runs? const { a, ...rest } = { a: 1, b: { c: 2 } }; const [, , ...tail] = 'hi';
Show answer
rest is { b: { c: 2 } }, and rest.b is the same object as the original b property, not a copy. tail is [], because the string 'hi' has only two characters, both of which are skipped, so the rest element collects an empty array.
Exercise
Why does const [...items, last] = [1, 2, 3]; fail, and how can you get the last element and all the others instead?
Show answer
A rest element must be the last item in the pattern, so this line is a SyntaxError. Use const last = arr.at(-1); const items = arr.slice(0, -1); instead.