{"id":3437,"date":"2024-09-23T23:08:34","date_gmt":"2024-09-23T21:08:34","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=3437"},"modified":"2024-09-23T23:09:37","modified_gmt":"2024-09-23T21:09:37","slug":"understanding-structuredclone-in-javascript","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2024\/09\/23\/understanding-structuredclone-in-javascript\/","title":{"rendered":"Deep Cloning with structuredClone() in JavaScript"},"content":{"rendered":"\n<h4><strong>What is&nbsp;<code>structuredClone()<\/code>?<\/strong><\/h4>\n\n\n\n<p>Here\u2019s another way to express it:<\/p>\n\n\n\n<p><code>structuredClone()<\/code> is a global function that was introduced in 2022, designed for deep cloning JavaScript objects. Unlike conventional methods like <code>JSON.stringify()<\/code> and <code>JSON.parse()<\/code>, which can have difficulties with intricate structures and circular references, <code>structuredClone()<\/code> effectively manages these complexities without issue.<\/p>\n\n\n\n<p>Let us explore how <code>structuredClone()<\/code> works, contrast it with the traditional methods of cloning using <code>JSON.stringify()<\/code> and <code>JSON.parse()<\/code>, and provide code examples to illustrate the differences.<\/p>\n\n\n\n<h4>What is Cloning?<\/h4>\n\n\n\n<p>Cloning in programming refers to creating a copy of an object. There are two types of cloning:<\/p>\n\n\n\n<ol><li><strong>Shallow Cloning<\/strong>: Only the first level of the object is copied. Nested objects are still referenced.<\/li><li><strong>Deep Cloning<\/strong>: A complete copy of the object is made, including all nested objects.<\/li><\/ol>\n\n\n\n<h4>The Problem with&nbsp;<code>JSON.stringify()<\/code>&nbsp;and&nbsp;<code>JSON.parse()<\/code><\/h4>\n\n\n\n<p>The traditional approach to deep cloning in JavaScript often involves using <code>JSON.stringify()<\/code> to convert an object into a JSON string and then parsing that string back into an object using <code>JSON.parse()<\/code>. While this method works for many cases, it has its limitations:<\/p>\n\n\n\n<ul><li><strong>Loss of Functions<\/strong>: Methods are not preserved.<\/li><li><strong>Date Objects<\/strong>: Dates are converted to strings.<\/li><li><strong>Undefined Values<\/strong>:&nbsp;<code>undefined<\/code>&nbsp;is lost in the process.<\/li><li><strong>Circular References<\/strong>: If an object contains circular references, this method will throw an error.<\/li><\/ul>\n\n\n\n<h4>Introducing&nbsp;<code>structuredClone()<\/code><\/h4>\n\n\n\n<p>The <code>structuredClone()<\/code> function provides a robust solution for deep cloning. It can handle a wider variety of data types and structures, including:<\/p>\n\n\n\n<ul><li>Functions<\/li><li>Dates<\/li><li>Maps and Sets<\/li><li>Circular references<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>let clone = structuredClone(value);\n<\/code><\/pre>\n\n\n\n<h4>Code Examples<\/h4>\n\n\n\n<p>Let\u2019s look at some examples to illustrate the differences between these methods.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const original = {\n  name: \"Alice\",\n  age: 30,\n  nested: {\n    hobbies: &#91;\"reading\", \"traveling\"],\n  },\n};\n\n\/\/ Using JSON.stringify and JSON.parse\nconst jsonClone = JSON.parse(JSON.stringify(original));\n\nconsole.log(jsonClone); \/\/ { name: 'Alice', age: 30, nested: { hobbies: &#91; 'reading', 'traveling' ] } }\nconsole.log(jsonClone.nested === original.nested); \/\/ true (shallow copy)\n\n\/\/ Using structuredClone\nconst structuredCloneResult = structuredClone(original);\n\nconsole.log(structuredCloneResult); \/\/ { name: 'Alice', age: 30, nested: { hobbies: &#91; 'reading', 'traveling' ] } }\nconsole.log(structuredCloneResult.nested === original.nested); \/\/ false (deep copy)\n<\/code><\/pre>\n\n\n\n<p><strong>Explanation<\/strong>: In the example above, using <code>JSON.stringify()<\/code> results in a shallow copy of the nested object, meaning changes to <code>nested<\/code> in either <code>original<\/code> or <code>jsonClone<\/code> will affect the other. In contrast, <code>structuredClone()<\/code> creates a true deep copy.<\/p>\n\n\n\n<h5>Example 2: Handling Circular References<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>const circularObj = {};\ncircularObj.self = circularObj;\n\n\/\/ Using JSON.stringify and JSON.parse\ntry {\n  const jsonClone = JSON.parse(JSON.stringify(circularObj));\n} catch (error) {\n  console.log(\"JSON method error:\", error.message); \/\/ TypeError: Converting circular structure to JSON\n}\n\n\/\/ Using structuredClone\nconst structuredCloneCircular = structuredClone(circularObj);\nconsole.log(structuredCloneCircular.self === structuredCloneCircular); \/\/ true\n<\/code><\/pre>\n\n\n\n<p><strong>Explanation<\/strong>: The <code>JSON<\/code> methods fail with circular references, throwing an error. However, <code>structuredClone()<\/code> handles it gracefully, maintaining the reference.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h5>Example 3: Handling Special Data Types<\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>const dateObj = {\n  date: new Date(),\n};\n\n\/\/ Using JSON.stringify and JSON.parse\nconst jsonDateClone = JSON.parse(JSON.stringify(dateObj));\nconsole.log(jsonDateClone.date instanceof Date); \/\/ false (not a Date object)\n\n\/\/ Using structuredClone\nconst structuredDateClone = structuredClone(dateObj);\nconsole.log(structuredDateClone.date instanceof Date); \/\/ true (still a Date object)\n<\/code><\/pre>\n\n\n\n<p><strong>Explanation<\/strong>: When using <code>JSON.stringify()<\/code>, the Date object is converted to a string. In contrast, <code>structuredClone()<\/code> preserves the original data type.<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h5>Conclusion<\/h5>\n\n\n\n<p>The introduction of <code>structuredClone()<\/code> in JavaScript provides developers with a powerful tool for deep cloning objects. It overcomes the limitations of traditional methods like <code>JSON.stringify()<\/code> and <code>JSON.parse()<\/code>, making it a valuable addition to the JavaScript language. Whether you&#8217;re dealing with complex data structures or need to maintain data types, <code>structuredClone()<\/code> is the way to go for reliable cloning in your applications.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is&nbsp;structuredClone()? Here\u2019s another way to express it: structuredClone() is a global function that was introduced in 2022, designed for deep cloning JavaScript objects. Unlike conventional methods like JSON.stringify() and JSON.parse(), which can have difficulties with intricate structures and circular references, structuredClone() effectively manages these complexities without issue. Let us explore how structuredClone() works, contrast [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1963,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[5,83],"tags":[904,902,903],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3437"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=3437"}],"version-history":[{"count":2,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3437\/revisions"}],"predecessor-version":[{"id":3439,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3437\/revisions\/3439"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/1963"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=3437"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=3437"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=3437"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}