Take a look at the following code snippets and compare the results:

Code Example_01

In the code above, when we change the name of the clone from “Lily” to “Camellia”, the original flower is also changed.

Code Example_02

Now, let’s look at the second example. Interestingly, after we change the name of the clone to “Camellia”, the original flower name is still “Lily”.

Did you spot the biggest difference?

In the first example, flower has a nested object within an array while the second example does not. This tricky question teaches us one lesson: It’s important to understand deep and shallow copies, or you might mutate the data unintentionally.

The first example creates a shallow copy, which means that only the top-level values are duplicated but the nested object is still pointing to the same object in memory. As a result, when you change the name of the clone, the original flower gets updated too.

However, the second example creates a deep copy, meaning that the clone and the flower are referencing different objects in memory. Thus, all the values are unrelated.

Let’s try to visualize what happened here with an analogy. It’s not a perfect analogy but hopefully it will help you understand the concept better.


Shallow Copy Analogy

Below we have two plants: obj1 and its clone. In this analogy, the leaf represents the property {color: “green”}. These two plants are interconnected and sharing the same pot (i.e. pointing to the same object in memory).

When I modify the leaf color of the clone, the leaf of the original obj1 will also change to {color: “pink”}. BOOM! Just like magic.

Shallow Copy Analogy

#web-development #coding #programming #es6 #javascript

Learn Deep & Shallow Copy  with Tricky JavaScript Questions
4.55 GEEK