Deep copy vs shallow copy in Javascript

Shallow copy

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.

Deep copy

Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

Primitive data types

When you create these values, they are tightly coupled with the variable they are assigned to. They only exist once. That means you do not really have to worry about copying primitive data types in JavaScript. When you make a copy, it will be a real copy. Let’s see an example:

let a = 5;
let b = a;
b = 6;
console.log(a); // 5
console.log(b); // 6

Reference data types

Technically, arrays are also objects, so they behave in the same way. I will go through both of them in detail later.
Here it gets more interesting. These values are actually stored just once when instantiated, and assigning a variable just creates a pointer (reference) to that value.

With Object Create an object a with property test with value test1 and then copy b = a and then change value test in object b.Let see example:

Shallow copy

const a = 5;
const b = a;

b.test = 'test2'; //Shallow copy

console.log(a); // test 2
console.log(b); // test 2

Deep copy

const a = { test: 'test1' }

//you can use spread or Object.assign() method for clone an object

const b = {...a}; // or const b = Object.assign({},a);

b.test = 'test2'; // Deep copy

console.log(a); // test 1
console.log(b); // test 2

Making deep copies without thinking

const a = { test: 'test1' }
const b = JSON.parse(JSON.stringify(a));
b.test = 'test2';

console.log(a); // test 1
console.log(b); // test 2

With Arrays

Copying arrays is just as common as copying objects.You can use some ways for deep copy are Spread Operator,Array Functions, Nested Array. Let see an example below:

const a = [1,2,3]
let b = [...a] // Spread Operator
let b = => item) // Array Functions
let b = a.slice(0) // Array Functions

let b = JSON.parse(JSON.stringify(a)) // Nested Array

Conclusion In the end, you know should use the copy with reference data types for some case you want to copy an object or array split with original and some ways how to make a deep copy.

Thanks for reading. Please share your experiences, questions and feedback below!


Share this