creation

Object.assign

Copies all enumerable own properties from one or more source objects to a target object, then returns the modified target. Performs a shallow merge, invoking source getters and target setters.

Object.assign(target, ...sources)

Parameters

Parameter Purpose
target The object to receive copied properties (mutated in place)
...sources One or more source objects whose enumerable own properties are copied
returns The mutated target object

Examples

console.log(Object.assign({}, { a: 1 }, { b: 2 }));

Logs { a: 1, b: 2 } — common shallow-merge idiom

const target = { a: 1 };
Object.assign(target, { a: 99, b: 2 });
console.log(target);

Logs { a: 99, b: 2 } — later sources overwrite earlier keys

const nested = { user: { name: 'Ada' } };
const copy = Object.assign({}, nested);
copy.user.name = 'Grace';
console.log(nested.user.name);

Logs 'Grace' — nested objects are shared (shallow copy)

const s = Symbol('id');
console.log(Object.assign({}, { [s]: 1, a: 2 }));

Logs { a: 2, [Symbol(id)]: 1 } — Symbol keys ARE copied

Gotcha

Shallow copy — nested objects/arrays are shared by reference. Copies enumerable own properties including Symbols; it INVOKES source getters (reading their value) and INVOKES target setters (rather than overwriting them).

Related methods

← All JS Object methods · Array methods · Spread vs rest