The new way of deep-copying in JS, Stop using libraries!

Agenda

  • What’s a shallow copy?
  • Example of shallow copy
  • What’s a deep copy?
  • How can I use a deep copy in JavaScript (the old way)?
  • What’s the difference between deep copy and shallow copy?
  • The old way to make a deep copy in Js
  • The new way to make a deep copy in js
  • Conclusion

What’s a shallow copy mean?

What’s deep copy?

How can I use a deep copy in JavaScript (the old way)?

Let’s simplify the code that we wrote above and know what its shortcomings and tripwires are?

  • Recursive data structure: JSON.parse() will throw when you give it a recursive data structure. This can happen quite easily when working with linked lists or trees.
  • JSON.stringify() will throw if the value contains other JS built-ins like Map, Set, Date, RegExp or ArrayBuffer , is a little bit unpredictable, see the following example
JSON.stringify({ key: undefined });
JSON.stringify({ key: function(){} });
// all will be converted to just "{}"

The new way to make a deep copy in js

Features and limitations

Supported types

  • All primitive types
  • Boolean objects
  • Strings objects
  • Date
  • RegExp
  • Blob
  • File
  • FileList
  • ArrayBuffer
  • etc…
  • Function objects cannot be duplicated by the structured clone algorithm; attempting to throw a DataCloneError exception.
  • Cloning DOM nodes likewise throws a DataCloneError exception.
  • Certain object properties are not preserved:
  • The lastIndex property of RegExp objects is not preserved.
  • Property descriptors, setters, getters, and similar metadata-like features are not duplicated. For example, if an object is marked read-only with a property descriptor, it will be read/write in the duplicate, since that’s the default.
  • The prototype chain is not walked or duplicated.

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abdlrahmansaber

Abdlrahmansaber

Software engineer, Problem solver, Geek.