Problem Statement
What does Object.assign() do?
Explanation
Object assign copies all enumerable properties from one or more source objects to a target object.
It returns the modified target object. Properties in later sources overwrite properties in earlier sources.
Object assign creates a shallow copy, meaning nested objects are still referenced.
It is commonly used for cloning objects or merging multiple objects.
The spread operator is now preferred over Object assign for most use cases.
Code Solution
SolutionRead Only
// Merging objects
const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4};
const merged = Object.assign({}, obj1, obj2);
console.log(merged); // {a: 1, b: 2, c: 3, d: 4}
// Cloning object
const original = {x: 1, y: 2};
const clone = Object.assign({}, original);
clone.x = 10;
console.log(original.x); // 1 (unchanged)
// Override properties
const defaults = {color: 'red', size: 'medium'};
const options = {size: 'large'};
const config = Object.assign({}, defaults, options);
console.log(config); // {color: 'red', size: 'large'}
// Modifying target
const target = {a: 1};
Object.assign(target, {b: 2}, {c: 3});
console.log(target); // {a: 1, b: 2, c: 3}
// Modern spread operator (preferred)
const merged2 = {...obj1, ...obj2};
const clone2 = {...original};
// Shallow copy warning
const nested = {x: 1, y: {z: 2}};
const shallowCopy = Object.assign({}, nested);
shallowCopy.y.z = 3;
console.log(nested.y.z); // 3 (also changed!)Practice Sets
This question appears in the following practice sets:
