DEV Community

Cover image for Shallow Copy vs. Deep Copy in Javascript

Shallow Copy vs. Deep Copy in Javascript

Jenish Dabhi on March 18, 2024

JavaScript is a high-level, dynamically typed client-side scripting language. Shallow Copy : In JavaScript, a shallow copy refers to creating a ...
Collapse
 
jonrandy profile image
Jon Randy 🎖️

A deep copy is better achieved using structuredClone - it is slower, but way more powerful.

Collapse
 
jenishdabhi profile image
Jenish Dabhi

 Thank you @jonrandy for sharing your perspective!

Collapse
 
miketalbot profile image
Mike Talbot ⭐

stringify and parse will play havoc if your object has references to the same objects within it - the copy will have all of the data, but they'll all be different objects afterwards.

Collapse
 
tqbit profile image
tq-bit

Not only that, it'll throw errors if you have circular references in the object you want to clone

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Very good point :)

Collapse
 
jenishdabhi profile image
Jenish Dabhi

Hey @miketalbot , You are correct that using JSON.stringify and JSON.parse for deep copying objects can lead to issues when there are references to the same objects within the object structure.

Collapse
 
jangelodev profile image
João Angelo

Hi Jenish Dabhi,
Your tips are very useful
Thanks for sharing

Collapse
 
mashrafi_01 profile image
Muttaqin Mashrafi

Awesome 💯 keep it up