Cloning an object in JavaScript is a common task, especially when you want to work with a copy without altering the original. But the way you clone depends on whether you need a shallow copy or a deep copy.
Shallow Copy
A shallow copy duplicates only the first level of the object. If your object has nested objects or arrays, they will still reference the same memory.
- Ways to create a shallow copy:
- Using the spread operator:
const original = { name: 'Alice', age: 25 };
const clone = { ...original };
Using Object.assign():
const clone = Object.assign({}, original);
Deep Copy
A deep copy creates a completely independent copy, including all nested structures.
- Common methods for deep copying:
- Using JSON.parse(JSON.stringify(obj)):
const deepClone = JSON.parse(JSON.stringify(original));
Note: This method doesn't work well with functions, undefined, or special types like Date.
Using libraries like Lodash:
const _ = require('lodash');
const deepClone = _.cloneDeep(original);
Tips:
- Use shallow copy for simple flat objects.
- Use deep copy when the object has nested elements or you want full separation.