SyntaxStudy
Sign Up
JavaScript Object Spread and Object.assign()
JavaScript Intermediate 7 min read

Object Spread and Object.assign()

Object Spread and Object.assign()

Copying and merging objects are everyday tasks in JavaScript, especially when managing state immutably. Two mechanisms address this: the spread operator in object literals (ES2018) and the older Object.assign() function (ES2015).

Object Spread

Inside an object literal, ...source copies all own enumerable properties from source into the new object. Properties listed after a spread override earlier ones with the same key, making it easy to update specific properties while preserving the rest.

Object.assign(target, ...sources)

Object.assign copies properties into target and returns target. It mutates the target, so pass an empty object {} as the first argument when you want a fresh copy. It is functionally equivalent to spread for most use cases.

Shallow Copy Warning

Both spread and Object.assign perform only a shallow copy. Nested objects are shared by reference, so mutating a nested property of the copy also mutates the original.

Example
const defaults = { theme: 'light', lang: 'en', debug: false };
const userPrefs = { lang: 'fr', debug: true };
const config = { ...defaults, ...userPrefs };
console.log(config); // { theme:'light', lang:'fr', debug:true }
const original = { a: 1, nested: { b: 2 } };
const copy = { ...original };
copy.a = 99;
copy.nested.b = 99;
console.log(original.a);        // 1   — safe
console.log(original.nested.b); // 99  — shared!
const merged = Object.assign({}, defaults, userPrefs);
console.log(merged);
Pro Tip

Use structuredClone(obj) for a true deep copy in modern environments. For older environments, JSON.parse(JSON.stringify(obj)) works for plain data but drops functions, Dates become strings, and circular references throw.