Merge configuration objects
Combine configuration defaults with user-provided overrides while keeping the selected target object.
JavaScript · Function
Object.assign() copies enumerable own properties from one or more sources into a target object. It mutates and returns the target, with later sources winning when keys overlap.
Object.assign() takes a target followed by zero or more sources. It copies each source's enumerable own properties into the target, in argument order, and returns that same target object; later sources replace earlier values for duplicate keys.
Object.assign(target)
Object.assign(target, source1)
Object.assign(target, source1, source2)
Object.assign(target, source1, source2, /* …, */ sourceN)| Name | Type | Description |
|---|---|---|
target | any | The object receiving copied properties; a primitive target is converted to an object. |
source1, …, sourceN | any | One or more source objects whose enumerable own properties are applied; null and undefined sources are ignored. |
The modified target object.
const target = { a: 1 };
const source = { b: 2, a: 3 };
const result = Object.assign(target, source);
console.log(result); // { a: 3, b: 2 }
console.log(result === target); // trueThe source properties are copied into the target; the later source value replaces the earlier value for the same key.
Combine configuration defaults with user-provided overrides while keeping the selected target object.
Add enumerable methods or data properties to an existing object or prototype.
Create a shallow copy when nested references may intentionally remain shared.
It copies enumerable own properties from each source into the target and returns the modified target. The target is mutated, and later sources take precedence when keys collide.
Follow-up: How would you preserve property descriptors instead? Use Object.getOwnPropertyDescriptor() with Object.defineProperty(), because Object.assign() assigns values rather than copying descriptors.
The target is converted to an object, so a primitive target can be accepted and boxed. With no source arguments, the converted target is returned.
Follow-up: What happens when a source is null or undefined? It is ignored rather than converted or rejected.
Object.assign() performs a shallow copy: an object-valued property contributes its reference, not a recursively cloned object. Use structuredClone() or another deep-cloning approach when independent nested data is required.
Follow-up: Does it copy symbol keys? Yes, enumerable own Symbol properties are copied along with enumerable own string properties.
Object.getOwnPropertyDescriptor()Object.defineProperty()structuredClone()Object.create()