Structured clone

The structured clone algorithm is a mechanism in JavaScript that can be used to duplicate complex objects. It’s commonly used when invoking structuredClone() or when transferring data between Workers via postMessage(), storing objects with IndexedDB, or copying objects for other APIs.

When cloning an object, the algorithm recursively traverses through the input object while keeping track of previously visited references in a map to avoid getting stuck in infinite loops.

What doesn’t work with structured clone

  • Function objects can’t be duplicated by the structured clone algorithm; attempting to throws a DataCloneError exception.
  • Cloning DOM nodes likewise throws a DataCloneError exception.
  • Certain object properties aren’t preserved:
    • The lastIndex property of RegExp objects isn’t preserved.
    • Property descriptors, setters, getters, and similar metadata-like features aren’t duplicated. For example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that’s the default.
    • The prototype chain isn’t walked or duplicated.

For more information on Structured clone visit MDN Web Docs.