How do you clone an object or array in JavaScript?
Explore different ways to clone objects and arrays without mutating the original data.
Advertisement
Question
How do you clone an object or array in JavaScript?
Answer
You can clone objects and arrays using several methods:
Using spread operator:
const arr = [1, 2, 3];
const copy = [...arr];
Using Object.assign():
const user = { name: 'Ali' };
const clone = Object.assign({}, user);
Deep copy example:
const deepClone = JSON.parse(JSON.stringify(obj));
Real-World Example
When managing React state, always clone objects or arrays before updating them to maintain immutability.
Quick Practice
Clone an array [10, 20, 30], modify its first element, and confirm the original array isn’t affected.
Summary
Use spread or Object.assign for shallow copies; use JSON methods or libraries for deep cloning.
Does spread operator create a deep copy?
No, it only creates a shallow copy — nested objects still reference the original.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement