JSON.parse(JSON.stringify()) vs structuredClone: What Survives the Copy
I copied objects with JSON.parse(JSON.stringify(obj)) for years. It works right up until the object holds something JSON has no idea about. I ran a test on Node.js 22 with four values that break the trick: const original = { date : new Date ( "2026-01-01T00:00:00Z" ) , map : new Map ( [ [ "a" , 1 ] ] ) , undef : undefined , nan : NaN , } ; const viaJson = JSON . parse ( JSON . stringify (…
JSON.parse(JSON.stringify()) has been used for years to copy objects, but it has limitations. This method works as long as the object only contains JSON-compatible types: object, array, string, number, boolean, and null. However, when the object includes more complex types such as Date, Map, undefined, NaN, or Infinity, JSON.parse(JSON.stringify()) fails to accurately replicate the original object.
When tested on Node.js 22, the following issues were observed: the Date type was converted to a string, the Map became an empty object instead of a Map, the undefined property was removed entirely, and NaN turned into null. This method is essentially a serialization round trip rather than a true copy. However, structuredClone, a newer method, performs better in these scenarios.
It handles Date, Map, Set, RegExp, typed arrays, ArrayBuffer, and circular references. structuredClone copies Date instances as Date objects, maintains Map and Set structures, preserves undefined properties, and retains NaN and Infinity values. When working with class instances, structuredClone copies the instance's prototype and fields, but it does not preserve property descriptors or getters.
To ensure a class instance retains its behavior, one should define a custom clone() method within the class. In summary, for simple JSON-compatible data, either JSON.parse(JSON.stringify()) or structuredClone can be used interchangeably. For copying objects containing complex types like Date, Map, Set, or class instances, structuredClone is the recommended approach.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to