Copying an object
1. Shallow copy
Creates a new object, but nested objects are copied by reference.
Way 1: Spread (...)
javascript
const user = { name: 'Tim', age: 25 };
const clone = { ...user };
console.log(clone); // { name: 'Tim', age: 25 }
console.log(clone === user); // falseFast, convenient, and modern. But nested structures (objects, arrays) remain references to the original:
javascript
const user = { name: 'Tim', address: { city: 'Kyiv' } };
const clone = { ...user };
clone.address.city = 'Lviv';
console.log(user.address.city); // "Lviv" (affects the original)Way 2: Object.assign()
javascript
const user = { name: 'Tim', age: 25 };
const clone = Object.assign({}, user);
console.log(clone); // { name: 'Tim', age: 25 }Same as spread, also a shallow copy.
Way 3: Via a loop (manual way)
javascript
const clone = {};
for (const key in user) {
if (user.hasOwnProperty(key)) {
clone[key] = user[key];
}
}Old-fashioned, but works even in old browsers.
2. Deep copy
Creates a fully independent copy - even nested objects are not linked to the original.
Way 1: structuredClone() (modern and safe)
javascript
const user = {
name: 'Tim',
address: { city: 'Kyiv', zip: 12345 }
};
const clone = structuredClone(user);
clone.address.city = 'Lviv';
console.log(user.address.city); // "Kyiv"Supported in all modern browsers and Node.js 17+. It copies:
- nested objects, arrays, dates, Map, Set, and so on;
- it does not copy functions and prototypes (they are lost).
Way 2: Via JSON.parse(JSON.stringify())
javascript
const user = { name: 'Tim', address: { city: 'Kyiv' } };
const clone = JSON.parse(JSON.stringify(user));
clone.address.city = 'Lviv';
console.log(user.address.city); // "Kyiv"Works almost everywhere, but:
- functions,
undefined,Symbol,Date,Map,Set, andBigIntare lost; - it can be slow on large structures.
Way 3: Libraries (lodash, Ramda, etc.)
javascript
import _ from 'lodash';
const clone = _.cloneDeep(user);The most reliable way for complex structures - it preserves types, nesting, and runs fast.
SUMMARY
| Copy type | Way | Copies nested objects? | Preserves types (Date, Map, Set)? |
|---|---|---|---|
| Shallow | { ...obj }, Object.assign() | No | Yes |
| Deep | structuredClone() | Yes | Yes |
| Deep (old way) | JSON.parse(JSON.stringify()) | Yes | No |
| Deep (reliable) | _.cloneDeep() | Yes | Yes |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.