JavaScript Object Spread: Merge Shallow Records
Quick answer
Object spread copies enumerable own properties into a new object. It supports convenient record updates and default overrides.
How it works
In {...defaults, ...settings}, later properties replace earlier keys. Both string and symbol keys can be copied. Getters are read and their current values become ordinary own data properties; the prototype and descriptors of the source are not cloned. Null and undefined sources contribute nothing.
const defaults = {size: 4, color: "red"};const config = {...defaults, color: "blue"};console.log(config.size, config.color, defaults.color);Expected output in Node.js:
4 blue redThe later color wins without modifying defaults.
const a = {nested: {count: 1}};const b = {...a};b.nested.count = 3;console.log(a.nested.count, a === b);Expected output in Node.js:
3 falseNested values retain identity.
Common mistakes
Order matters. {...settings, ...defaults} can unintentionally overwrite user settings. Nested objects are still shared.
Practice
Merge two preference records and reverse the spread order to compare outcomes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Object Spread: Merge Shallow Records — Knowledge Check
Apply the taught concept and predict the output.
Which source properties are copied by object spread?
When two spread sources supply the same key, which wins?
Does object spread preserve a source property getter as a getter?
What is the exact console output in JavaScript Object Spread: Merge Shallow Records example 1?
const defaults = {size: 4, color: "red"};const config = {...defaults, color: "blue"};console.log(config.size, config.color, defaults.color);What is the exact console output in JavaScript Object Spread: Merge Shallow Records example 2?
const a = {nested: {count: 1}};const b = {...a};b.nested.count = 3;console.log(a.nested.count, a === b);