Course contentsShow
← JavaScript
Lesson 972 of 2,72322. Spread and RestFree lesson

Merging Multiple Objects

Combine multiple objects into one using spread, with later objects overwriting earlier properties.

Merging Multiple Objects

What you'll learn: How to combine two or more objects into a single object using the spread operator, where properties from later objects override earlier ones.

The Core Idea

When you spread multiple objects into a new object literal, JavaScript merges them from left to right. If the same property appears in multiple objects, the rightmost value wins—it overwrites any earlier values for that property.

Think of it like layering transparencies: each new layer you place on top shows through, but wherever it has content, it covers what's beneath.

Basic Syntax

const defaults = { theme: 'light', fontSize: 14 };
const userPrefs = { fontSize: 18 };

const settings = { ...defaults, ...userPrefs };
console.log(settings);
// { theme: 'light', fontSize: 18 }

Here, fontSize from userPrefs overwrites the fontSize from defaults, but theme remains because only defaults provided it.

Merging Three or More Objects

const base = { a: 1, b: 2 };
const middle = { b: 3, c: 4 };
const top = { c: 5, d: 6 };

const merged = { ...base, ...middle, ...top };
console.log(merged);
// { a: 1, b: 3, c: 5, d: 6 }

The order matters: base is applied first, then middle overwrites b, then top overwrites c.

Practical Use Case

This pattern is perfect for configuration objects where you want defaults but allow user customization:

const defaultConfig = { timeout: 3000, retries: 3 };
const userConfig = { retries: 5 };

const finalConfig = { ...defaultConfig, ...userConfig };
// { timeout: 3000, retries: 5 }

Key Takeaway: Spread multiple objects left-to-right to merge them, with later objects overwriting properties from earlier ones—a clean, immutable way to combine configurations or settings.