Gyaan

Shallow Copy & Deep Copy

beginner objects arrays references
Shallow Copy
let a
let b = a
↓           ↓
[1, 2, 3, 4]
same memory
Deep Copy
let a
let b = [...a]
↓           ↓
[1, 2, 3, 4]
[1, 2, 3, 4]
different memory

Shallow Copy

The shallow copy of an object will refer to the same memory as the original array.

let a = [1,2,3,4] // Memory Address : 10225
let b = a;         // Memory Address : 10225 (same)
b.push(5)          // Changes in b
console.log(a)     // [1,2,3,4,5]

Deep Copy

The memory reference will not be the same when copying using a deep copy method. Using the Spread Operator or map:

// Using map
let a = [1,2,3,4]
let b = a.map((e) => e);
b.push(5)
console.log(a) // [1,2,3,4]
// Using spread operator
let a = [1,2,3,4]
let b = [...a];
b.push(5)
console.log(a) // [1,2,3,4]