Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is structured clone algorithm different from deep copy

Tags:

javascript

There's a MDN article that states that:

The structured clone algorithm is a new algorithm defined by the HTML5 specification for serializing complex JavaScript objects. It's more capable than JSON

So, I believe this means that it's more capable than cloning in this way:

JSON.parse(JSON.stringify(obj))

suggested in this thread. The JSON way has many drawbacks like not supporting circular references, dropping everything not supported by JSON spec, like functions, and representing Date object as strings.

I then thought that structured clone algorithm is deep copy algorithm implemented by many libraries. However, it's listed on the same page with the words:

If you want a deep copy of an object (that is, a recursive copy of all nested properties, walking the prototype chain), you must use another approach. The following is a possible example.

So now I'm confused and don't know what is structured algorithm or how it's different from deep copy. Any help? I don't want to read a spec, maybe some libraries implemented it, so I can read their source code.

like image 979
Max Koretskyi Avatar asked Nov 08 '16 13:11

Max Koretskyi


Video Answer


1 Answers

Structued Clone Algorithm is one of the way to deep copy your JavaScript object. Since this api is not exposed directly so we have alternate ways by which we can use it.

Why do we use it anyway if we have JSON.parse and JSON.stringify?

Because JSON.parse(JSON.stringify(obj)) has some limitations like you have mentioned, which are, they do not serialize the circular object or things like Map, Set, Date, RegEx etc.

So, this is where this api(Structure clone) comes into play.

How to use it?

Since this api(Structured Cloning) is not directly exposed but it is used by some other apis. So we can use those other apis in order to use Structured Cloning.

Such apis are:

  1. history.pushState
  2. MessageChannel
  3. Notification

To see the examples and comparison between these apis, I highly recommend Surma blogpost.


Update

So, finally Structured Clone api is directly exposed in some of the browsers(see supported versions and coverage) under the function name structuredClone().

How to use it?

Example with date object:

const a = { x: 20, date: new Date() };
const b = structuredClone(a); // { x: 20, date: <date object> }

Note: with JSON.stringify the date object would have been serialized with Date.prototype.toJSON

Example with circular object:

const a = { x: 20, date: new Date() };
a.c = a;
const b = structuredClone(a); // { x: 20, date: <date object>, c: <circular ref> }

Note: with JSON.stringify it will throw a TypeError

like image 171
Sachin Bhandari Avatar answered Oct 26 '22 03:10

Sachin Bhandari