Skip to content

Object rest/spread properties: copy and omit (ES2018)

  • 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.

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).

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' }

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.

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 false
Paris

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 undefined
false true
setter 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.

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 } true
TypeError: Cannot destructure 'null' as it is null.
o-1: status, total

The 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.

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 a TypeError.
  • 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 shared
console.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 3
99 true
TypeError: {(intermediate value)} is not iterable

Pitfalls:

  • Spreading very large arrays into a call. Math.max(...hugeArray) passes every element as an argument and can throw a RangeError once the engine’s argument limit is exceeded. Use reduce or a loop.
  • Expecting a deep copy. [...lines] copies the array, not the objects inside it.
  • Putting rest anywhere but last. function f(...a, b) and const [...a, b] = x are syntax errors.

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.

  • 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 returns new Order(...).
  • Getting precedence backwards. { ...overrides, ...defaults } lets defaults win. Put the strongest source last.
  • Overriding with undefined. { ...defaults, ...{ pageSize: undefined } } sets pageSize to undefined, 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 } = maybeNull throws. Default it: = maybeNull ?? {}.
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

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.

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.

  • 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.assign sets them, which differs for setters and __proto__.
  • Never spread untrusted input straight into stored data; allow-list fields first.