Merging Objects with Overrides
What you'll learn: How later properties in a spread operation override earlier ones when merging objects.
When you merge multiple objects using the spread operator, JavaScript follows a simple rule: properties from objects on the right win. If two objects have the same property name, the value from the object that appears later in the spread sequence overwrites the earlier value.
Think of it like layers of paint: each new coat covers what was underneath. The last color you apply is what you see.
How Override Order Works
const defaults = { color: 'blue', size: 'medium', active: true };
const userPrefs = { color: 'red', size: 'large' };
const config = { ...defaults, ...userPrefs };
// { color: 'red', size: 'large', active: true }
Here, userPrefs overrides color and size from defaults, but active remains from defaults since userPrefs doesn't have it.
Practical Use Case: Default + Overrides
This pattern is extremely common for configuration objects:
const defaultSettings = {
theme: 'light',
notifications: true,
language: 'en'
};
const userSettings = {
theme: 'dark'
};
const finalSettings = { ...defaultSettings, ...userSettings };
// { theme: 'dark', notifications: true, language: 'en' }
You start with sensible defaults, then let user preferences override only what they've specified.
Order Matters
const a = { x: 1 };
const b = { x: 2 };
const c = { x: 3 };
const result1 = { ...a, ...b, ...c }; // { x: 3 }
const result2 = { ...c, ...b, ...a }; // { x: 1 }
The rightmost object always wins. This gives you precise control over which values take precedence.
Key Takeaway: When spreading multiple objects, properties from later objects override properties from earlier ones—spreading reads left-to-right, and the last value for each property name wins.