JavaScript question detail
What is structuredClone and how is it used for deep copying objects?
In JavaScript, structuredClone() is a built-in method used to create a deep copy of a value. It safely clones nested objects, arrays, Maps, Sets, Dates, TypedArrays, and even circular references — without sharing references to the original value. This prevents accidental mutations and makes it useful for state management and data processing.
For example, the below snippet demonstrates deep cloning of a nested object,
const originalObject = {
name: "Deep Copy Test",
nested: {
value: 10,
list: [1, 2, 3]
},
};
const deepCopy = structuredClone(originalObject);
// Modify cloned value
deepCopy.nested.value = 99;
deepCopy.nested.list.push(4);
console.log(originalObject.nested.value); // 10
console.log(deepCopy.nested.value); // 99
console.log(originalObject.nested.list); // [1, 2, 3]
console.log(deepCopy.nested.list); // [1, 2, 3, 4]