Back to Home
Objects

How to Shallow Copy Objects

Use Object.assign() or spread operator for shallow copies

Quick Answer (2024 ES6+ Way)

javascript
const original = { a: 1, b: 2 };
const copy1 = Object.assign({}, original);
const copy2 = { ...original };
console.log(copy2); // { a: 1, b: 2 }

Live Example

javascript
const defaults = { theme: 'light', lang: 'en' };
const userPrefs = { lang: 'fr', fontSize: 14 };

// Merge objects (right overrides left)
const config = Object.assign({}, defaults, userPrefs);
console.log(config);

// Add properties while copying
const enhanced = Object.assign({}, original, {
  timestamp: Date.now(),
  version: '1.0'
});

// Multiple sources
const merged = Object.assign({}, obj1, obj2, obj3);

Common Variations

Modify While Copying
javascript
const copy = Object.assign({}, original, {
  modified: true,
  timestamp: Date.now()
});
Clone Array of Objects
javascript
const copied = arr.map(obj => ({ ...obj }));

❌ Don't Do This (Outdated Way)

Avoid thinking it creates deep copies

javascript
// DON'T DO THIS - nested objects are still referenced
const copy = Object.assign({}, { nested: { val: 1 } });
copy.nested.val = 2; // Affects original!

Browser Support

Works in all modern browsers (ES2015+)

#objects#copy#assign