Object rest/spread properties: copy and omit (ES2018)
What you’ll learn
Section titled “What you’ll learn”- How object spread merges objects and how object rest omits properties.
- Exactly which properties are copied: own, enumerable, string and symbol keys.
- Why spread is not the same as
Object.assign(), and when the difference bites. - How the ES2015 array spread and rest parameters relate to the object forms.
Summary
Section titled “Summary”TL;DR: In an object literal, { ...source } copies source’s own enumerable properties into the new object; later properties overwrite earlier ones. In destructuring, const { a, ...rest } = obj puts every own enumerable property except the ones you named into a new object rest.
Both were added in ECMAScript 2018, extending the array spread and rest syntax of ES2015 (covered in Array spread and rest parameters) to objects. Every current browser and runtime supports them (see Compatibility).
The problem it solves
Section titled “The problem it solves”Before ES2018, merging meant Object.assign({}, a, b), where forgetting the {} mutated a, and omitting a field meant copying the object and then deleting the field.
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs). All outputs shown were produced with Node.js 22.23. The examples use an invented order-management app, OrdersPortal.
const defaults = { currency: 'USD', pageSize: 25, theme: 'light' };const userPrefs = { pageSize: 50 };const user = { id: 'u-7', email: 'ana@example.test', passwordHash: 'x9f...', role: 'admin' };
// Before (ES2015): Object.assign for merging, copy-then-delete for omitting.const settingsOld = Object.assign({}, defaults, userPrefs);const publicOld = Object.assign({}, user);delete publicOld.passwordHash;
// After (ES2018): spread to merge, rest to omit.const settings = { ...defaults, ...userPrefs };const { passwordHash, ...publicUser } = user;
console.log(settingsOld, settings);console.log(publicOld, publicUser);Output:
{ currency: 'USD', pageSize: 50, theme: 'light' } { currency: 'USD', pageSize: 50, theme: 'light' }{ id: 'u-7', email: 'ana@example.test', role: 'admin' } { id: 'u-7', email: 'ana@example.test', role: 'admin' }How it works
Section titled “How it works”Both forms use the spec operation CopyDataProperties. It skips null and undefined, wraps other primitives, and for each own enumerable key (strings, then symbols) not excluded, reads the value (running getters) and defines a data property on the new object.
Spread in object literals
Section titled “Spread in object literals”const tag = Symbol('tag');const source = { a: 1, [tag]: 'sym' };Object.defineProperty(source, 'hidden', { value: 'not enumerable', enumerable: false });
// Own enumerable string and symbol keys are copied; non-enumerable ones are not.console.log({ ...source });
// Later properties win, so order expresses precedence.console.log({ status: 'draft', ...{ status: 'paid' } }, { ...{ status: 'paid' }, status: 'draft' });
// null and undefined are ignored; strings spread their indexes; other primitives add nothing.console.log({ ...null, ...undefined, ...'ok', ...42, ...true });
// Getters on the source run once; the copy holds a plain data property.let reads = 0;const live = { get total() { reads++; return 99; } };const snap = { ...live };console.log(snap, Object.getOwnPropertyDescriptor(snap, 'total'), reads);
// The prototype is not copied: class instances lose their methods.class Money { constructor(v) { this.v = v; } format() { return `$${this.v}`; } }const copy = { ...new Money(5) };console.log(copy, typeof copy.format, copy instanceof Money);
// Shallow: nested objects are shared.const order = { id: 'o-1', address: { city: 'Lyon' } };const clone = { ...order };clone.address.city = 'Paris';console.log(order.address.city);Output:
{ a: 1, [Symbol(tag)]: 'sym' }{ status: 'paid' } { status: 'draft' }{ '0': 'o', '1': 'k' }{ total: 99 } { value: 99, writable: true, enumerable: true, configurable: true } 1{ v: 5 } undefined falseParisSpread defines; Object.assign sets
Section titled “Spread defines; Object.assign sets”Object.assign writes with ordinary assignment, so it triggers setters on the target and treats a "__proto__" key as the prototype setter. Spread always creates a fresh object and defines own properties, so neither happens. This matters for objects parsed from JSON, where "__proto__" is an ordinary key:
const payload = JSON.parse('{"__proto__": {"isAdmin": true}, "name": "ana"}');
const viaSpread = { ...payload };const viaAssign = Object.assign({}, payload);
console.log(Object.hasOwn(viaSpread, '__proto__'), viaSpread.isAdmin);console.log(Object.hasOwn(viaAssign, '__proto__'), viaAssign.isAdmin);
const target = { set name(v) { console.log('setter ran with', v); } };Object.assign(target, { name: 'assign' });const merged = { ...target, ...{ name: 'spread' } };console.log(Object.getOwnPropertyDescriptor(merged, 'name'));Output:
true undefinedfalse truesetter ran with assign{ value: 'spread', writable: true, enumerable: true, configurable: true}With Object.assign, the payload replaced the copy’s prototype, so isAdmin is inherited.
Rest in destructuring
Section titled “Rest in destructuring”const tag = Symbol('tag');const order = { id: 'o-1', status: 'paid', total: 40, [tag]: 'x' };
const { id, ...rest } = order;console.log(id, rest); // rest includes the symbol key
// Computed keys can be excluded too.const field = 'total';const { [field]: _omitted, ...withoutTotal } = order;console.log(withoutTotal);
// Rest only collects own enumerable properties, into a plain object.const child = Object.create({ inherited: true }, { own: { value: 1, enumerable: true } });const { ...ownOnly } = child;console.log(ownOnly, Object.getPrototypeOf(ownOnly) === Object.prototype);
// Destructuring null or undefined throws, even with only a rest element.try { const { ...r } = null; } catch (e) { console.log(e.constructor.name + ':', e.message); }
// In parameters.function toRow({ id, ...fields }) { return `${id}: ${Object.keys(fields).join(', ')}`; }console.log(toRow(order));Output (the TypeError message is V8’s wording):
o-1 { status: 'paid', total: 40, [Symbol(tag)]: 'x' }{ id: 'o-1', status: 'paid', [Symbol(tag)]: 'x' }{ own: 1 } trueTypeError: Cannot destructure 'null' as it is null.o-1: status, totalThe rest element must be last and cannot have a trailing comma. const { ...a, b } = {} is a SyntaxError (“Rest element must be last element” in V8). Only one rest element is allowed per pattern.
Array spread and rest parameters
Section titled “Array spread and rest parameters”The array forms came first, in ECMAScript 2015; the object forms on this page extended them in 2018. The same ... token means two opposite things depending on position:
- Spread expands an iterable into individual elements: in an array literal (
[...a, ...b]) or in a function call (Math.max(...prices)). It works with any iterable, so[...new Set(skus)],[..."text"]and[...map.keys()]all work. Spreading a non-iterable such as a plain object into an array throws aTypeError. - Rest collects values into a real array: a rest parameter (
function log(level, ...parts)) gathers the remaining arguments, and an array rest element (const [first, ...others] = list) gathers the remaining items. Rest must be last, and a function can have only one rest parameter, which cannot have a default value.
Rest parameters replace the old arguments object, which is array-like rather than a real array and does not exist in arrow functions. Array spread replaces concat, slice() copies and fn.apply(null, args). Like object spread, array spread makes a shallow copy: the new array holds the same object references.
const lines = [{ sku: "MUG-01", qty: 1 }, { sku: "TEE-03", qty: 2 }];const extra = [{ sku: "CAP-07", qty: 1 }];
const merged = [...lines, ...extra, { sku: "BAG-05", qty: 1 }];console.log(merged.map((l) => l.sku));
const prices = [12, 9.5, 18];console.log(Math.max(...prices), [...new Set(["MUG-01", "MUG-01", "TEE-03"])], [..."A-1"]);
function audit(action, orderId, ...details) { return `${action} ${orderId}: ${details.length ? details.join(", ") : "no details"} (${Array.isArray(details)})`;}console.log(audit("ship", "ord-1", "express", "gift wrap"));console.log(audit("cancel", "ord-2"));
const [head, ...tail] = merged;console.log(head.sku, tail.length);
const copy = [...lines];copy[0].qty = 99; // shallow: the line objects are sharedconsole.log(lines[0].qty, copy !== lines);
try { console.log([...{ sku: "MUG-01" }]);} catch (error) { console.log(error.name + ":", error.message);}Output:
[ 'MUG-01', 'TEE-03', 'CAP-07', 'BAG-05' ]18 [ 'MUG-01', 'TEE-03' ] [ 'A', '-', '1' ]ship ord-1: express, gift wrap (true)cancel ord-2: no details (true)MUG-01 399 trueTypeError: {(intermediate value)} is not iterablePitfalls:
- Spreading very large arrays into a call.
Math.max(...hugeArray)passes every element as an argument and can throw aRangeErroronce the engine’s argument limit is exceeded. Usereduceor a loop. - Expecting a deep copy.
[...lines]copies the array, not the objects inside it. - Putting rest anywhere but last.
function f(...a, b)andconst [...a, b] = xare syntax errors.
Realistic example
Section titled “Realistic example”OrdersPortal uses them to layer settings, strip secrets before logging, and build a PATCH body of changed, editable fields.
const DEFAULTS = Object.freeze({ currency: 'USD', pageSize: 25, filters: { status: 'all' } });
function resolveSettings(saved = {}, overrides = {}) { return { ...DEFAULTS, ...saved, ...overrides, // Nested objects need their own spread, or the defaults object is shared. filters: { ...DEFAULTS.filters, ...saved.filters, ...overrides.filters }, };}
function redact(record) { const { password, cardNumber, ...safe } = record; return safe;}
// Send only editable fields that changed.function buildPatch(before, after) { const { id, createdAt, ...editable } = after; return Object.fromEntries(Object.entries(editable).filter(([k, v]) => before[k] !== v));}
console.log(resolveSettings({ pageSize: 50, filters: { from: '2026-11-01' } }, { currency: 'EUR' }));console.log(DEFAULTS.filters);console.log(redact({ email: 'ana@example.test', password: 'hunter2', plan: 'pro' }));
const before = { id: 'o-9', createdAt: '2026-11-01', note: '', qty: 1 };const after = { ...before, note: 'leave at door', qty: 2, createdAt: '2026-01-01' };console.log(buildPatch(before, after));Output:
{ currency: 'EUR', pageSize: 50, filters: { status: 'all', from: '2026-11-01' }}{ status: 'all' }{ email: 'ana@example.test', plan: 'pro' }{ note: 'leave at door', qty: 2 }Object.freeze is shallow too: without the nested spread, every settings object would share the mutable DEFAULTS.filters. redact is a deny-list, so a new secret field leaks until someone adds it; for data leaving a trust boundary, prefer an allow-list. ESLint’s no-unused-vars option ignoreRestSiblings stops it flagging password and cardNumber.
Common mistakes
Section titled “Common mistakes”- Expecting a deep copy. Nested objects and arrays are shared. Spread each level you change, or use
structuredClone()for a full deep copy of plain data. - Spreading class instances. The copy is a plain object: methods on the prototype, private fields and the class identity are lost. Use a method like
withQty(n)that returnsnew Order(...). - Getting precedence backwards.
{ ...overrides, ...defaults }lets defaults win. Put the strongest source last. - Overriding with
undefined.{ ...defaults, ...{ pageSize: undefined } }setspageSizetoundefined, because the key exists. Drop undefined values first if “missing” should mean “use the default”. - Destructuring a value that may be
null.const { a, ...rest } = maybeNullthrows. Default it:= maybeNull ?? {}.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Use |
|---|---|
| New object merged from several sources | { ...a, ...b } |
| Copy of an object without some keys | const { key, ...rest } = obj |
| Update an existing object in place (keep its identity, run its setters) | Object.assign(target, changes) |
| Deep copy of plain data | structuredClone(obj) |
| Copy including getters, setters and non-enumerable properties | Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj)) |
| Copy or concatenate arrays | array spread, see Array spread and rest parameters |
Compatibility
Section titled “Compatibility”According to MDN’s browser compatibility data, both spread in object literals and rest in object destructuring are supported in Chrome 60, Edge 79, Firefox 55, Safari 11.1 (Safari on iOS 11.3), Node.js 8.3.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported them.
TypeScript: with target below ES2018, TypeScript 6.0 rewrites object spread to Object.assign calls (checked with target ES2017) and object rest to a __rest helper. The assignment-based form brings back the setter and __proto__ behavior described above, so use target ES2018 or later when that matters.
Interview questions
Section titled “Interview questions”1. What is the difference between { ...a } and Object.assign({}, a)?
For plain data they produce the same result. The difference is that Object.assign uses assignment, so it runs setters on the target and treats a __proto__ key as a prototype change, and it can write into an existing object. Spread always creates a new object and defines own data properties.
2. Which properties does { ...obj } copy?
Own, enumerable properties, with both string and symbol keys. Inherited and non-enumerable properties are skipped, getters are invoked and stored as values, and nested objects are shared (shallow copy).
3. How do you remove a property from an object without mutating it?
Destructure it out and keep the rest: const { password, ...safe } = user. For a dynamic key, use a computed pattern: const { [key]: _, ...rest } = obj.
4. Senior scenario: an API handler merges the request body into a stored record with const updated = { ...record, ...req.body } before saving. What problems do you see?
It is a mass-assignment risk: a client can overwrite role, id or ownerId just by sending them. Validate the body against a schema and merge only an allow-list of editable fields. Nested objects in the body also replace stored ones wholesale, which can drop data, so merge them explicitly. Spread keeps a JSON __proto__ key as a harmless own property, but unexpected keys should still be stripped.
Key takeaways
Section titled “Key takeaways”- Object spread and rest (ES2018) copy own enumerable string and symbol properties into a new plain object.
- Later sources win in spread; named keys are excluded from rest.
- Copies are shallow and lose prototypes, methods and accessors.
- Spread defines properties;
Object.assignsets them, which differs for setters and__proto__. - Never spread untrusted input straight into stored data; allow-list fields first.
Related pages
Section titled “Related pages”- Destructuring: the patterns that object rest extends.
- Object.assign: the older merge API and its differences.
- Object.entries: filter or transform properties when rest is not enough.
- Object.hasOwn: check own properties safely.
- Array.prototype.with: the array counterpart for immutable updates.
- Objects, arrays and JSON
Official references
Section titled “Official references”- ECMAScript Language Specification,
CopyDataProperties(current draft; used by object spread and rest since ECMAScript 2018) - ECMAScript 2018 Language Specification (ECMA-262, 9th edition), Object Initializer
- TC39 proposal: Object Rest/Spread Properties
- MDN: Spread syntax
- MDN: Destructuring
- MDN: structuredClone()
- MDN: Rest parameters