JavaScript Nested Cloning

Table of contents

In JavaScript, objects and variables when the same value is assigned to multiple variables, then the reference (address) of the object is shared between the variables

So, if you change the value of one property in one of the variables, that would in turn change the value for all the variables, essentially they are homogenous twins with the same brain

Cloning:

By normal assign operator, you can't duplicate, but by using cloning you can duplicate the object, separate twins with separate brains 🧠. Some of the approaches are

By cloning, when you change the property values, the other variables will not get affected. But wait, what about the nested values?

Even after cloning, how did the value of the property of basicDetails change to 177? This is because basic Cloning using a spread operator or Object.assign() clones only the first level of properties, hence metadata in itself is an object and the reference is copied.

To clone the whole object with its nested properties, you can write a deepClone function that checks every property and then clones it, or use the inbuilt method called structuredClone which does the deep nesting cloning for you. An example by using structuredClone method

More about structuredClone here. That's all for today folks!! Share to your fellow devs so everyone can learn

0
Subscribe to my newsletter

Read articles from Abu Bakker Siddiq H directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abu Bakker Siddiq H
Abu Bakker Siddiq H