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
Object.fromEntries
Transforms a list of key-value pairs into an object — the inverse of Object.entries. Introduced in ES2019 and accepts any iterable of [key, value] pairs, including Map.
Object.create
Creates a new object with the specified prototype and optional property descriptors. Pass null to create an object with no prototype at all.
Object.defineProperties
Defines multiple new or modified properties on an object by supplying a descriptors map. The batch-form counterpart of Object.defineProperty.
Object.defineProperty
Defines a new property directly on an object, or modifies an existing one, with fine-grained control over its descriptor. Returns the object.