Shallow Copy & Deep Copy in Javascript
Tom and Jerry are best friends. They have a big math exam coming up. Tom studied hard and is ready, but Jerry didn't study and decides to copy Tom's answers.
Shallow Copy: A Quick Cheat
Scenario:
During the exam,Jerry copies Tom’s answers and also understands why Tom chose those answers.
Jerry takes notes and studies Tom’s rough work.
If Tom changes his answer for the first question to "A" Jerry understands the reason and also changes his answer to "A"
Explanation:
This is like a shallow copy in Javascript.
Jerry’s answers are initially the same as Tom’s, but they are separate after copying. Changes Tom makes later don’t affect Jerry’s answers.
A shallow copy means copying the main answers, but not any changes made later.
Deep Copy: A Thorough Cheat
Scenario:
During the exam, Jerry sits next to Tom and copies Tom's answers exactly as they are.
If Tom writes "B" for the second question, Jerry writes "B" too.
After copying, if Tom changes his answer for the Second question to "A" Jerry doesn't notice and keeps "B"
Explanation:
This is like a shallow copy in Javascript.
Jerry’s answers are initially the same as Tom’s, but they are separate after copying. Changes Tom makes later don’t affect Jerry’s answers.
Summary
Shallow Copy:
Creates a new reference to the same object.
Changes to the original object are reflected in the shallow copy.
Deep Copy:
Creates a completely new object with the same values.
Changes to the original object do not affect the deep copy.
The choice between shallow and deep copying depends on whether you need independent copies of the objects or if referencing the same object suffices for your use case.
Thanks................
Follow Me on Linkedin: https://www.linkedin.com/in/bhavesh-nandave-3aa4a51ba/
Follow Me on Twitter:https://twitter.com/Bhavesh_Nandave
Subscribe to my newsletter
Read articles from Bhavesh Nandave directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Bhavesh Nandave
Bhavesh Nandave
Hello, My Name is Bhavesh Nandave. Currently, I am a Freshman studying at Pune University Pursuing a Bachelor of Engineering in (Automation & Robotics). I have a strong ambition to learn every day & apply my learnings to wonderful web creations. I Have Keen Intrest in Artificial Intelligence, Machine Learning, and DevOps.