Spread (objects)
Learn to spread an object's properties into another with ....
Spread (objects)
Spread works on objects too. Put ... in front of an object inside curly braces and its properties expand one by one. Writing const merged = { ...defaults, fontSize: 14 } adds fontSize next to every property of defaults.
This is the same as Object.assign({}, defaults, { fontSize: 14 }), only shorter and clearer. It produces a new object; the source objects are not changed.
The override rule
When two objects share a key, the last one wins. Writing const settings = { ...defaults, ...userPrefs } lets the keys in userPrefs override those in defaults.
This is intentional: you put defaults first and user preferences second. The user keeps the defaults for fields they left blank, and their own value wins where they set one.
Exercise Merge the configuration
Create an object called defaultConfig with theme and lang properties. Create a second object called userConfig with only a lang property. Build a third object called settings by merging with spread: defaultConfig first, userConfig second. Log settings with console.log.
Show example solution
const defaultConfig = { theme: "dark", lang: "en" };
const userConfig = { lang: "fr" };
const settings = { ...defaultConfig, ...userConfig };
console.log(settings);
Test yourself
-
What does `{ ...a, ...b }` produce?
const a = { x: 1 }; const b = { y: 2 }; const c = { ...a, ...b };- It deletes the `a` object
- An object with only the properties of `a`
- A new object combining the properties of `a` and `b`
- A two-element array
Show answer
A new object combining the properties of `a` and `b` — Correct. Properties from both objects are gathered into a new object.
-
Override the defaults
const defaults = { theme: "light", volume: 50 }; const userPrefs = { volume: 80 }; const settings = ____; console.log(settings);Show answer
const defaults = { theme: "light", volume: 50 }; const userPrefs = { volume: 80 }; const settings = {...defaults, ...userPrefs}; console.log(settings); -
Match the concepts
- object spread
- Expands properties into a new object
- array spread
- Expands elements into a new array
- last one wins
- Same-key clash