Sub topic 5
Collecting the Rest in Patterns
Earlier chapters showed how to pull named or positioned values out of objects and arrays. Often you want a few values by name and everything else in one bundle. A rest element (in array patterns) or a rest property (in object patterns) does that. You write it as ...name at the end of a pattern.
This chapter assumes you know let and const, basic array and object destructuring, default values in patterns, and the difference between reference and primitive values. The same ... token also appears in function parameter lists and as spread in literals and calls. Those uses get their own chapters. This one covers only patterns on the left side of =.
Rest Elements in Array Patterns
An array rest element gathers every remaining value from the source into a new array:
const [head, second, ...tail] = [10, 20, 30, 40, 50];
console.log(head); // 10
console.log(second); // 20
console.log(tail); // [30, 40, 50]
console.log(Array.isArray(tail)); // trueThe rest variable is always a real array, even when nothing is left to collect:
const [only, ...nothing] = ['solo'];
console.log(only); // 'solo'
console.log(nothing); // [] (an empty array, never undefined)
const [...copy] = [];
console.log(copy); // []Your code can therefore call tail.length or tail.map(...) without first checking for undefined.
Skipped slots and rest elements work together. Empty commas consume positions before the rest begins:
const [, , ...fromThird] = ['a', 'b', 'c', 'd'];
console.log(fromThird); // ['c', 'd']Holes Become undefined
Array destructuring reads values by iterating, and iterating a sparse array yields undefined for each hole. The rest array therefore contains explicit undefined values where the source had holes:
const sparse = [1, , 3];
const [, ...restOfSparse] = sparse;
console.log(restOfSparse); // [undefined, 3]
console.log(1 in sparse); // false (a real hole)
console.log(0 in restOfSparse); // true (an actual undefined value)A Rest Element Can Be a Pattern
The target after ... in an array pattern does not have to be a plain variable. It can be another array or object pattern, which then destructures the collected array:
const [first, ...[second, third]] = [1, 2, 3, 4];
console.log(first, second, third); // 1 2 3
const [label, ...{ length: count }] = ['items', 'x', 'y', 'z'];
console.log(label, count); // 'items' 3This works, but it rarely reads better than listing the positions directly. It is mostly useful for reading length off the remainder, as shown above.
Rest Properties in Object Patterns
An object rest property collects the own, enumerable properties that the pattern did not already name into a new plain object:
const product = { id: 42, title: 'Lamp', price: 30, stock: 5 };
const { id, ...details } = product;
console.log(id); // 42
console.log(details); // { title: 'Lamp', price: 30, stock: 5 }A property counts as "already named" if it appears anywhere in the pattern. Renaming it or giving it a default still excludes it from the rest object:
const product = { id: 42, title: 'Lamp', price: 30 };
const { id: productId, discount = 0, ...others } = product;
console.log(productId); // 42
console.log(discount); // 0
console.log(others); // { title: 'Lamp', price: 30 }The pattern lists discount, but the source has no discount property, so the exclusion has no effect on the result.
What Gets Copied and What Doesn't
The rules in the diagram lead to some behavior that surprises people.
Symbol keys are included. An enumerable symbol-keyed property is copied just like a string key:
const tag = Symbol('tag');
const { a, ...withSymbol } = { a: 1, b: 2, [tag]: 'meta' };
console.log(withSymbol.b); // 2
console.log(withSymbol[tag]); // 'meta'Non-enumerable and inherited properties are left out. Methods defined on a class live on the prototype, so the rest object doesn't get them. The result is also a plain object, not an instance of the class:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.hypot(this.x, this.y);
}
}
const { x, ...remaining } = new Point(3, 4);
console.log(remaining); // { y: 4 }
console.log(remaining instanceof Point); // false
console.log(typeof remaining.length); // 'undefined'
const settings = { mode: 'fast' };
Object.defineProperty(settings, 'secret', { value: 'hidden', enumerable: false });
const { ...visible } = settings;
console.log(visible); // { mode: 'fast' }Getters are run and their results are stored as plain values. The rest object receives a data property, not a copy of the getter:
let calls = 0;
const source = {
a: 1,
get stamp() {
calls += 1;
return `call ${calls}`;
},
};
const { a, ...snapshot } = source;
console.log(snapshot.stamp); // 'call 1'
console.log(snapshot.stamp); // 'call 1' (fixed value, getter not re-run)
console.log(Object.getOwnPropertyDescriptor(snapshot, 'stamp').get); // undefinedArrays can be destructured as objects. Indexes are own enumerable keys, while length is not enumerable, so length is left out:
const { 0: firstLetter, ...otherIndexes } = ['a', 'b', 'c'];
console.log(firstLetter); // 'a'
console.log(otherIndexes); // { '1': 'b', '2': 'c' }Array Rest vs Object Rest
| Aspect | Array rest element | Object rest property |
|---|---|---|
| Source must be | Iterable | Any value except `null` or `undefined` |
| Result type | New `Array` | New plain object (`Object.prototype`) |
| Collects | Every value the iterator yields after the earlier positions | Own enumerable string and symbol keys not named in the pattern |
| Empty result | `[]` | `{}` |
| Target after `...` | Variable, or a nested array/object pattern | Variable only (in declarations) |
| Default allowed on rest | No | No |
| Position | Must be last | Must be last |
Syntax Rules and Errors
The rest element or property must come last, and a trailing comma after it is not allowed. Each of these lines is a SyntaxError, so they are shown as comments:
// const [...start, end] = [1, 2, 3]; // SyntaxError: rest element must be last
// const [a, ...b,] = [1, 2, 3]; // SyntaxError: no trailing comma after rest
// const { ...all, id } = { id: 1 }; // SyntaxError: rest property must be last
// const [...items = []] = []; // SyntaxError: rest cannot have a default
// const { ...{ a } } = { a: 1 }; // SyntaxError: object rest needs a plain targetTo get the last element of an array, use arr.at(-1) or arr[arr.length - 1]. A pattern can't collect "everything except the end".
Since a rest can't have a default, the defaults that matter are on the whole source. With array rest you already get [] when values run out. If the source itself might be undefined, give the surrounding pattern a default instead, for example const [first, ...more] = list ?? [];.
In destructuring assignment (as opposed to a declaration), an object rest target can be any assignable reference, including a property on another object. Wrap the statement in parentheses:
let kind;
const bucket = {};
({ kind, ...bucket.extra } = { kind: 'event', at: 1700, source: 'ui' });
console.log(kind); // 'event'
console.log(bucket.extra); // { at: 1700, source: 'ui' }Gotcha: Array Rest Drains the Whole Iterator
Ordinary array destructuring stops reading once it has filled its named positions. A rest element keeps pulling values until the iterator reports it is done. With a generator you can watch this happen:
function* numbers() {
for (let n = 1; n <= 4; n++) {
console.log(`yield ${n}`);
yield n;
}
}
const [one] = numbers(); // logs: yield 1
console.log(one); // 1
const [uno, ...more] = numbers(); // logs: yield 1, yield 2, yield 3, yield 4
console.log(more); // [2, 3, 4]With an infinite iterator, such as a generator wrapped in while (true), a rest element never finishes and the program hangs. Take a bounded slice before destructuring.
Common Mistakes
- Expecting
undefinedfor an empty remainder. Array rest gives[]and object rest gives{}. Check.lengthorObject.keys(...).lengthif you need to know whether anything was collected. - Expecting class methods or prototype data in the rest object. Only own enumerable properties are copied, and the result is always a plain object.
- Treating the rest object as a deep copy. Nested objects are shared with the source.
- Destructuring
nullorundefined.const { ...r } = nullthrows aTypeError, just like any other object pattern.
Exercise
Given const cfg = { url: '/api', retries: undefined, timeout: 500 };, what do retries and opts hold after const { url: endpoint, retries = 3, ...opts } = cfg;? And what does rest hold after const [, ...rest] = 'hey';?
Show answer
retries is 3, because the source value is undefined and the default applies. opts is { timeout: 500 }, because url (renamed) and retries (defaulted) are both named in the pattern and so are excluded. A string is iterable, so rest is ['e', 'y'].
Exercise
Why does const { x, ...r } = new Point(3, 4) produce an r that has no length method, and why is r instanceof Point false?
Show answer
Object rest copies only own enumerable properties into a new plain object whose prototype is Object.prototype. The length method lives on Point.prototype, so it is inherited, not owned, and is skipped. The new object is not created by Point, so instanceof Point is false.
Exercise
Rewrite const [...start, last] = items; so it runs and gives you both the last item and all items before it, without mutating items.
Show answer
A rest must come last, so use array methods instead: const last = items.at(-1); const start = items.slice(0, -1);. If you control the order, reversing is also possible: const [lastItem, ...reversedStart] = [...items].reverse();, but slice and at are clearer.