Object Spread vs Object.assign
You'll learn: When to use the spread operator versus Object.assign() for copying and merging objects, and how they differ.
Two Ways to Do the Same Thing
Both the spread operator ({...obj}) and Object.assign() can shallow copy and merge objects, but they have subtle differences in syntax and behavior.
Object.assign() Syntax
const original = { name: 'Alice', age: 30 };
// Object.assign() mutates the first argument
const copy1 = Object.assign({}, original);
// Merging multiple objects
const defaults = { theme: 'light', volume: 50 };
const userPrefs = { volume: 80 };
const settings = Object.assign({}, defaults, userPrefs);
console.log(settings); // { theme: 'light', volume: 80 }
Spread Operator Syntax
const original = { name: 'Alice', age: 30 };
// Spread always creates a new object
const copy2 = { ...original };
// Merging multiple objects
const defaults = { theme: 'light', volume: 50 };
const userPrefs = { volume: 80 };
const settings = { ...defaults, ...userPrefs };
console.log(settings); // { theme: 'light', volume: 80 }
Key Differences
Syntax: Spread is cleaner and more intuitive—it always creates a new object. Object.assign() requires passing an empty object {} as the first argument to avoid mutation.
Flexibility: Spread lets you easily add properties inline:
const settings = { ...defaults, volume: 100, newProp: 'value' };
When to Use Each: Modern JavaScript favors spread for its readability. Use Object.assign() when working with older codebases or when you need the explicit function call for compatibility reasons.
Key Takeaway: Both do shallow copies and merges, but spread syntax ({...obj}) is more concise and readable than Object.assign({}, obj) for creating new objects.