Deep Copy vs Shallow Copy In JS: Explained!🀌

Deep Copy vs Shallow Copy In JS: Explained!🀌

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?

  1. 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
    
  2. 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 πŸ˜†
    
  3. Using External Libraries:- There are external libraries like lodash that let you create deep copies.

     const _ = require('lodash');
     const copiedObj = _.cloneDeep(originalObj);
    
  4. 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. πŸŒŸπŸ”—

Β