structuredClone() a deep copy of the original value#
Is a method of that creates deep clone of a given object (includes nested fields).
This is useful when its tedious to use the spread operator { ...obj }
on a deeply nested object.
The purpose of cloning is that you would not have to accidentally mutate the original.
Usages#
JS
structuredClone(value);
structuredClone(value, options);
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone
Examples#
JS
const sample = {
id: 1,
name: {
first: 'John',
last: 'Doe',
},
};
const clone = { ...sample };
const trueClone = structuredClone(sample);
clone.name.first = 'James';
console.log(sample.name.first); // James
console.log(trueClone.name.first); // John
Warning
The spread operator { ...obj } does not create a "deep clone" of the object.
So for each nested object within its fields, you have to use the spread operator.
Which in this case structuredClone() already handled it for you.