How to Copy an Object in JavaScript?
In JavaScript, object copying can be:
- Shallow copy — only top-level properties are copied, nested objects are copied by reference.
- Deep copy — a complete independent copy is created, including nested objects and arrays.
Shallow Copying
Spread Operator "(...)"
const obj = { name: "Alice", age: 25 };
const copy = { ...obj };
- Simple and readable
- Only top level is copied
Object.assign()
const obj = { name: "Bob" };
const copy = Object.assign({}, obj);
- Alternative to spread
- Also shallow copy
Deep Copying
JSON.parse(JSON.stringify(...))
const original = { user: { name: "Tom" } };
const deepCopy = JSON.parse(JSON.stringify(original));
- Convenient and simple
- Doesn't copy functions,
undefined,Date,Map,Set, etc.
structuredClone() (built-in method)
const deepCopy = structuredClone(obj);
- Works with most structures (including
Map,Set,Date,Blob) - Safe and efficient
- Requires browser support (supported in modern browsers)
Manual Copying / Libraries
lodash.cloneDeep
import cloneDeep from 'lodash/cloneDeep';
const deepCopy = cloneDeep(obj);
- Suitable for complex objects
- Proven and reliable method
Important:
Simple reference copying (const copy = obj) doesn't create a new object — it's a reference to the same object in memory.