What is the difference between shallow copy and deep copy in JavaScript?
const original = { name: "Robin", skills: ["HTML"] };
const shallow = { ...original };
const deep = structuredClone(original);
original.skills.push("CSS");
console.log(shallow.skills);
console.log(deep.skills);
Output:
Tutorials Class - Output Window
[ "HTML", "CSS" ]
[ "HTML" ]
The spread { ...original } copies only the top level, so skills is still the same array. structuredClone() copies everything. (JSON.parse(JSON.stringify(obj)) also works, but it loses functions and dates.)
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |