JavaScript - Deep cloning Objects & arrays, structuredClone Method in javaScript

Veröffentlicht am: 08 November 2024
auf dem Kanal: CodeOneByOne
31
4

Did you know? You can now deep clone objects and arrays in JavaScript without any external libraries like Lodash! 🔥

With "structuredClone" method, JavaScript now has a built-in solution for deep cloning. This method creates an entirely independent copy of the original, even for nested objects, meaning changes to the clone won’t affect the original.

In the video below, I walk through two examples to illustrate the difference:

1) Shallow Clone with Spread Operator:
Using the spread operator ({ ...person1 }) only makes a shallow copy of the "person1" object. This means that while the top level is copied, any nested objects inside (like name in this case) are still linked to the original. If you modify "person2.name.firstName", it will also change "person1.name.firstName" since both objects share the same name reference.

2) Deep Clone with structuredClone –
With "structuredClone(person1)", a completely separate, deep copy of "person1" is created. This means each level of the object is cloned independently, including any nested objects. Now, when we change "person2.name.firstName", it has no effect on "person1.name.firstName". "structuredClone" ensures "person2" is a true duplicate, completely isolated from "person1".

This makes structuredClone a powerful tool for cases where you need a fully independent clone of an object, especially when dealing with complex, nested structures.
#js #javascriptdev #javascriptdeveloper #javascriptframework #javascript #javascripttutorial #javascriptengineer #javascriptprojects #frontenddevelopment #frontendinterview #frontenddeveloper #frontenddesign #frontenddeveloperlove #reactjsinterviewquestions #reactfrontend #react #reacts #reactfrontend #reactdevelopment #reactdeveloper


Auf dieser Seite können Sie das Online-Video JavaScript - Deep cloning Objects & arrays, structuredClone Method in javaScript mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer CodeOneByOne 08 November 2024 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 31 Mal angesehen und es wurde von 4 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!