Spread Operator
Spread Operator (…)
Section titled “Spread Operator (…)”Introduction
Section titled “Introduction”The spread operator ... “spreads” the properties of an object into a new object. It’s used for copying and merging objects.
Copying Objects
Section titled “Copying Objects”const original = { name: 'Alice', age: 25 };const copy = { ...original };
console.log(copy); // { name: 'Alice', age: 25 }console.log(copy === original); // false — different referenceMerging Objects
Section titled “Merging Objects”const user = { name: 'Alice' };const details = { age: 25, email: 'alice@email.com' };const preferences = { theme: 'dark' };
const merged = { ...user, ...details, ...preferences };// { name: 'Alice', age: 25, email: 'alice@email.com', theme: 'dark' }Overriding Properties
Section titled “Overriding Properties”const defaults = { theme: 'light', fontSize: 14 };const userSettings = { theme: 'dark' };
const settings = { ...defaults, ...userSettings };// { theme: 'dark', fontSize: 14 } — userSettings overridesShallow Copy Warning
Section titled “Shallow Copy Warning”const original = { name: 'Alice', address: { city: 'NYC' }};
const copy = { ...original };copy.address.city = 'LA';
console.log(original.address.city); // 'LA' — shallow!Summary
Section titled “Summary”...spreads properties into a new object- Used for copying and merging
- Later properties override earlier ones
- Only shallow copies — nested objects are shared