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

Publicado el: 08 noviembre 2024
en el canal de: 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


En esta página del sitio puede ver el video en línea JavaScript - Deep cloning Objects & arrays, structuredClone Method in javaScript de Duración hora minuto segunda en buena calidad , que subió el usuario CodeOneByOne 08 noviembre 2024, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 31 veces y le gustó 4 a los espectadores. Disfruta viendo!