Cloning means creating a copy of an object or array.
There are two main types:
- Shallow clone → copies only the first level.
- Deep clone → copies all nested levels.
1️⃣ Cloning an Array
✅ Shallow Clone
-
Using Spread Operator
const arr = [1, 2, 3]; const copy = [...arr]; console.log(copy); // [1, 2, 3] -
Using
slice()const arr = [1, 2, 3]; const copy = arr.slice(); -
Using
Array.from()const copy = Array.from(arr);
✅ Deep Clone
For nested arrays:
const nested = [[1, 2], [3, 4]];
const deepCopy = JSON.parse(JSON.stringify(nested));
2️⃣ Cloning an Object
✅ Shallow Clone
-
Using Spread Operator
const obj = { a: 1, b: 2 }; const copy = { ...obj }; -
Using
Object.assign()const copy = Object.assign({}, obj);
✅ Deep Clone
-
Using
JSON.parse(JSON.stringify())const deepObj = { a: 1, b: { c: 2 } }; const deepCopy = JSON.parse(JSON.stringify(deepObj));⚠️ Doesn’t work with functions,
undefined, or special types likeDate. -
Using Structured Clone (modern browsers)
const deepCopy = structuredClone(deepObj);
💡 In Short:
- Shallow clone:
...obj,Object.assign(), or[...arr]- Deep clone:
JSON.parse(JSON.stringify(obj)orstructuredClone()
Use deep cloning when objects have nested data that should not reference the original.