Object Spread Syntax Basics
You'll learn how to use the spread operator (...) to shallow copy and merge objects, just like you've been doing with arrays.
Using Spread with Objects
Remember how you used ... to copy and combine arrays? The same spread operator works with objects, letting you clone them or merge multiple objects into one.
The syntax looks like this:
const original = { name: 'Alice', age: 30 };
const copy = { ...original };
console.log(copy); // { name: 'Alice', age: 30 }
console.log(copy === original); // false (different object)
Merging Objects
You can spread multiple objects together. Properties from later objects overwrite earlier ones if they share the same key:
const defaults = { theme: 'light', notifications: true };
const userPrefs = { theme: 'dark' };
const settings = { ...defaults, ...userPrefs };
console.log(settings);
// { theme: 'dark', notifications: true }
Notice how theme: 'dark' replaced theme: 'light'.
Adding or Overriding Properties
You can add new properties or override specific ones while spreading:
const user = { id: 1, name: 'Bob' };
const updated = { ...user, name: 'Robert', active: true };
console.log(updated);
// { id: 1, name: 'Robert', active: true }
Think of It Like Unpacking
Imagine spreading an object is like unpacking a suitcase into a drawer. You're laying out all the contents. If you unpack two suitcases, items from the second one will sit on top of matching items from the first.
Key Takeaway: Object spread (...) creates a shallow copy of an object or merges multiple objects, with later properties overwriting earlier ones when keys match.