Understanding structuredClone: Efficient Object Cloning in JavaScript
Exploring the Benefits and Applications of JavaScript’s structuredClone Algorithm for Object Serialization and Deep Copying
Objects … in Javascript mostly every other thing is an Object or behaves like an Object.
And with Object, concept of referencing comes tied to it. Meaning, if we assign A to B, and does something to B, then A will get changed.
We can easily remove this referencing when assigning or passing objects by using few methods.
But before that let’s understand two buzz terms:
We have two types of copy constructs available in JS.
Shallow copy: only the first level of the object is copied. Deeper levels are referenced.
Deep Copy: all levels of the object are copied.
Until now we didn’t have any good and elegant way in JS to deeply copy an object. Every other available method has some downside. Here I’ve talked in detail about the downside of all the available methods and below is the downside described in brief.
- Using Destructuring : It only deep clones if the object or array is one level. (Only Do Shallow Copy)
- JSON.stringify() : If object contains date or function, those will be stringified too, and when we parse they won’t be useful. ( Referential Information Lost)
- Object.assign(): It only deep clones if the object or array is one level. (Only Do Shallow Copy)
- Lodash : Import Cost 5KB if we only add cloneDeep and ~25KB if we add while Library.
Solution
Now we have a native method available in JS, by which we can natively deep copy object in JS. And the name of the method is
Downside of using structuredClone:
1. It will only work on serialisable objects. It will not work on functions.
2. Functions can not be copied: If you want to copy an object that contains a function, the DataCloneError
exception will be thrown.
3. DOM nodes can’t be copied: It also throws the DataCloneError
when you attempt to clone DOM nodes.
4. Prototypes references lost: Structured cloning doesn’t duplicate the prototype chain. If you copy an instance of a Class
, the copied object will no longer be an instance of this Class
. A plain object is returned in place of the original Class
.
Although it has some downside, but in most of the cases it will serve the purpose, as normally we don’t add DOM tree in objects.