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

Published: 08 November 2024
on channel: 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


On this page of the site you can watch the video online JavaScript - Deep cloning Objects & arrays, structuredClone Method in javaScript with a duration of hours minute second in good quality, which was uploaded by the user CodeOneByOne 08 November 2024, share the link with friends and acquaintances, this video has already been watched 31 times on youtube and it was liked by 4 viewers. Enjoy your viewing!