Many of us (the folks who write code) have bumped into the word "copy" while doing our coding thing! It's like a buddy we meet a lot.
Now, before we get all serious about it, let's figure out what this "copy" deal is.
A copy is like making a twin β they might look alike, but they're not the same. Here's the tricky part: when you change one twin, you expect the other to just chill, right? But sometimes, that chill twin decides to change too!
Okay, now in the world of JavaScript, there's this cool idea: deep copy and shallow copy!
Stay with me to uncover the magic of these copy types! π©β¨
Let's look at the below code before we start diving into the explanation:-
const person = {
name: "Prabadhya",
age: 20
}
// Let's Create Copy
const personClone = person
// Modify Copy
personClone.name = "Mohit"
console.log(person); // Result { name: 'Mohit', age: 20 }
Beginner coders often get a surprise when they see the results of a certain code.
So, we made a "person" character, and then we copied it by putting it in a new "personClone" spot.
After that, we changed the "name" of the personClone and checked what happened when we looked at the "person." Now, here's the twist: we expected it to show the original person we made, but that didn't happen. Why? Because our personClone is a "Shallow Copy."
Now, how can we stop this surprising thing where changing a copy changes the original? Here comes the hero, the "deep copy."
But before we jump into the solution, let's grasp why this is happening in the first place. To get it, we need to peek behind the scenes at how JavaScript stores stuff. Imagine it like packing your stuff in memory boxes.
See, when we make a new box for something, like a name or a number, it gets its own space in memory. But when we make a new box and put the same thing from another box in it, something odd happens. Only basic stuff, like numbers and such, get new boxes. But for more complex things, like a whole character, we end up with a "Shallow Copy."
So, here's the thing: we're just getting started. The deep copy is like the superstar who can make sure our copies don't mess with the real thing. π
Curious to know more? Stay tuned for the magic behind deep copy! β¨
What is Shallow Copy?
A shallow copy is like creating a new passport β it's a distinct identity, but it still guides you back to the same home country. ππ
Picture this: the new variable you've crafted is like a tourist visa, directing you to the familiar streets of the original variable's neighborhood. It's not an entirely new house; it's just a pathway to the original one. So, any changes you make to this new tourist visa get echoed right back to the original passport, because they share the same home address. π π
But here's the hitch: Consider our previous example β it doesn't forge independence between these two objects; it crafts a bond of dependence. And that's a bit like having a duo that's always in sync, even when you want them to march to their beats. In the realm of coding, our desire is quite the opposite β we yearn for autonomy. We want each object to be its boss, not meddling with others. And sometimes, we fancy a touch of inheritance β like the cool traits you inherit from your folks β where we take some attributes from an existing object and blend in fresh ones, without turning the original upside down. ππ
So, while a shallow copy is like having a copycat buddy, it's not quite the solo act we often desire in our coding endeavors. We're on a quest for true autonomy and harmonious inheritance. ππ
But How can we solve this problem?
We can solve this with the help of a deep copy of the original object.
What is Deep Copy?
Think of a deep copy like creating a clone β not just a lookalike, but a whole new buddy with its own space to grow and change. π±π―ββοΈ
Here's the cool part: this clone doesn't share a room with the original; it's got its own pad in the same neighborhood. It's like moving into a new house, while your old house remains unchanged. π‘β¨
So, what's the deal with a deep copy?
Remember that example earlier? A deep copy is all about independence. It's like having two adventure buddies, each exploring their path in the coding jungle. Anything you do to one doesn't affect the other; they're free to do their own thing, without stepping on each other's toes. ππ
In the coding world, a deep copy is like a magic wand granting you the power of autonomy. It's creating something new without worrying about messing up the original. It's like a perfect harmony of doing your own thing without causing unintended mix-ups. π΅π
So, there you have it β a deep copy is like having a twin, each with its own story, but no drama between them. Ready to dive into the world of deep copy? πββοΈπ«
What are the best ways to create a deep copy in JS?
JSON.Parse(JSON.stringify) (Most Common one):- The easiest way to create a deep object is to use JSON.parse() with JSON.stringify().
const person = { name: "Prabadhya", age: 20 } const anotherPerson = JSON.parse(JSON.stringify(person)) // This will create a new copy of the person with new reference in // memory
Spread Operator (...) (Not recommended):- This is also one of the easiest ways to create a deep copy however this doesn't include deeply nested properties in the object meaning that those properties will still point to that old reference in memory.
const employee = { name:"Prabadhya", age:20, details:{ department:"IT", role:"Full Stack Engineer", gender:"Male" }, address:{ area:"814-B", city:"Mumbai", state:"Maharashtra" } } // Trying to create a deep copy using ...Spread Operator const deepCopyEmployee = {...employee} deepCopyEmployee.name = "Kriti" deepCopyEmployee.age = 22 console.log(deepCopyEmployee,employee) // In above Line you will see that deepCopyEmployee's properties changed and our employee's properties are still the same deepCopyEmployee.details.gender = "Female" // Now here what do you expect to see. console.log(deepCopyEmployee,employee) // In the above line you will see that gender property is also changed for Male employee LOL π
Using External Libraries:- There are external libraries like lodash that let you create deep copies.
const _ = require('lodash'); const copiedObj = _.cloneDeep(originalObj);
Structured Clone Algorithm (Web Workers):- The Structured Clone Algorithm is a mechanism used in modern Javascript to serialize and deserialize complex objects, allowing them to be transferred between different JavaScript contexts, such as between the main thread and Web Workers in web applications. This one is simple but not recommended for dealing with complex data and objects. This also doesn't clone functions , Maps, Sets and other Data Types.
const politician1 = { name:"Narendra Modi", party:"BJP", details:{ born:"XX-XX-XXXX", place:"Gujrat", currentPost:"PM of India" } } const politician2 = structuredClone(politician1) politician2.details.place = "Vadodra" console.log(politician1,politician2)
Conclusion: β¨ππ
Wrapping things up, let's remember that the world of object copying isn't always a one-size-fits-all affair. We've explored these methods, but they might not cover every intricate detail, like special objects or functions. It's like choosing the perfect tool for a specific task in your toolboxβpick what clicks best with your unique situation.
Now, here's the gold nugget: understanding the difference between deep copy and shallow copy isn't just a tech trickβit's your secret potion to becoming a coding maestro. Before you plunge into the exciting world of frameworks like React and Angular, let's rewind a bit. These concepts might seem like just lines of code, but they're the unsung heroes behind the scenes. Trust me, as a fellow traveler in the coding realm, I've seen many a newcomer grapple with these concepts when navigating those exciting frameworks.
So, that's a wrap for today, my friend! I hope you've savored this exploration into the fascinating universe of a deep and shallow copy.
If this journey has lit a spark in your curiosity, why not spread the word? A like, share, or even a friendly subscription can keep the knowledge flowing. Your support keeps this knowledge train chugging along.
Stay connected with me on this enlightening adventureβlet's continue uncovering the tech mysteries together, step by step. ππ
With heartfelt appreciation for your time and company...
Big thanks! ππ
P.S. Let's keep the conversation goingβfollow me for more captivating insights into the tech realm. After all, it's a human touch that makes the tech world truly exciting!
Follow me on Twitter and LinkedIn for more exciting tech adventures. ππ