Shallow Copy vs Deep Copy in JavaScript
JavaScript handles copying in two ways depending on the data type.
Primitive Values (Copy by Value) Primitive types include strings, numbers, booleans, symbols, bigInt, and null. When you copy a primitive, JavaScript creates a new independent version in memory.
Example: let a = 10; let b = a; b = 20; Result: a remains 10.
Non-Primitive Values (Copy by Reference) Objects and arrays work differently. They use references. When you copy an object, you only copy the pointer to its location in memory.
Example: let original = { name: "YOO" }; let copy = original; copy.name = "NEW"; Result: original.name is now "NEW".
The Difference: Shallow vs Deep
A shallow copy copies the top level of an object. If the object has nested objects, it still points to the original nested references. A deep copy creates a completely new object with all new values.
Think of it like pizza:
- Shallow Copy: You and a friend share one pizza. If your friend eats a slice, the pizza gets smaller for you too.
- Deep Copy: You both have your own separate pizzas. If your friend eats a slice, your pizza stays the same.
Shallow Copy Method You can use the spread operator (...) to make a shallow copy.
let original = { name: "YOO", details: { age: 22 } }; let copy = { ...original };
Warning: If you change original.details.age, the copy.details.age also changes. This is the shallow copy trap.
Deep Copy Methods
- structuredClone() This is a built-in function in modern browsers and Node.js. It handles nested structures perfectly.
Pros:
- Fast and native.
- Handles Dates, RegExp, and Maps.
Cons:
- Fails if the object contains functions or DOM nodes.
- JSON.parse(JSON.stringify()) This is an old trick where you turn an object into a string and back into an object.
Why avoid it:
- It loses data like undefined, Map, Set, or Infinity.
- It can corrupt certain values.
Source: https://dev.to/yogesh_992/shallow-copy-vs-deep-copy-in-java-script-explained-in-easiest-way-3dg5
