What is structuredClone()?

Here’s 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 it with the traditional methods of cloning using JSON.stringify() and JSON.parse(), and provide code examples to illustrate the differences.

What is Cloning?

Cloning in programming refers to creating a copy of an object. There are two types of cloning:

  1. Shallow Cloning: Only the first level of the object is copied. Nested objects are still referenced.
  2. Deep Cloning: A complete copy of the object is made, including all nested objects.

The Problem with JSON.stringify() and JSON.parse()

The traditional approach to deep cloning in JavaScript often involves using JSON.stringify() to convert an object into a JSON string and then parsing that string back into an object using JSON.parse(). While this method works for many cases, it has its limitations:

  • Loss of Functions: Methods are not preserved.
  • Date Objects: Dates are converted to strings.
  • Undefined Valuesundefined is lost in the process.
  • Circular References: If an object contains circular references, this method will throw an error.

Introducing structuredClone()

The structuredClone() function provides a robust solution for deep cloning. It can handle a wider variety of data types and structures, including:

  • Functions
  • Dates
  • Maps and Sets
  • Circular references
let clone = structuredClone(value);

Code Examples

Let’s look at some examples to illustrate the differences between these methods.

const original = {
  name: "Alice",
  age: 30,
  nested: {
    hobbies: ["reading", "traveling"],
  },
};

// Using JSON.stringify and JSON.parse
const jsonClone = JSON.parse(JSON.stringify(original));

console.log(jsonClone); // { name: 'Alice', age: 30, nested: { hobbies: [ 'reading', 'traveling' ] } }
console.log(jsonClone.nested === original.nested); // true (shallow copy)

// Using structuredClone
const structuredCloneResult = structuredClone(original);

console.log(structuredCloneResult); // { name: 'Alice', age: 30, nested: { hobbies: [ 'reading', 'traveling' ] } }
console.log(structuredCloneResult.nested === original.nested); // false (deep copy)

Explanation: In the example above, using JSON.stringify() results in a shallow copy of the nested object, meaning changes to nested in either original or jsonClone will affect the other. In contrast, structuredClone() creates a true deep copy.

Example 2: Handling Circular References
const circularObj = {};
circularObj.self = circularObj;

// Using JSON.stringify and JSON.parse
try {
  const jsonClone = JSON.parse(JSON.stringify(circularObj));
} catch (error) {
  console.log("JSON method error:", error.message); // TypeError: Converting circular structure to JSON
}

// Using structuredClone
const structuredCloneCircular = structuredClone(circularObj);
console.log(structuredCloneCircular.self === structuredCloneCircular); // true

Explanation: The JSON methods fail with circular references, throwing an error. However, structuredClone() handles it gracefully, maintaining the reference.

Example 3: Handling Special Data Types
const dateObj = {
  date: new Date(),
};

// Using JSON.stringify and JSON.parse
const jsonDateClone = JSON.parse(JSON.stringify(dateObj));
console.log(jsonDateClone.date instanceof Date); // false (not a Date object)

// Using structuredClone
const structuredDateClone = structuredClone(dateObj);
console.log(structuredDateClone.date instanceof Date); // true (still a Date object)

Explanation: When using JSON.stringify(), the Date object is converted to a string. In contrast, structuredClone() preserves the original data type.

Conclusion

The introduction of structuredClone() in JavaScript provides developers with a powerful tool for deep cloning objects. It overcomes the limitations of traditional methods like JSON.stringify() and JSON.parse(), making it a valuable addition to the JavaScript language. Whether you’re dealing with complex data structures or need to maintain data types, structuredClone() is the way to go for reliable cloning in your applications.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *