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

Pubblicato il: 08 novembre 2024
sul canale di: 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


In questa pagina del sito puoi guardare il video online JavaScript - Deep cloning Objects & arrays, structuredClone Method in javaScript della durata di ore minuti seconda in buona qualità , che l'utente ha caricato CodeOneByOne 08 novembre 2024, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 31 volte e gli è piaciuto 4 spettatori. Buona visione!