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
Nesta página do site você pode assistir ao vídeo on-line JavaScript - Deep cloning Objects & arrays, structuredClone Method in javaScript duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário CodeOneByOne 08 Novembro 2024, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 31 vezes e gostou 4 espectadores. Boa visualização!