![]() |
Introduction: What Does It Mean to Clone an Object?
In JavaScript, cloning an object means creating an independent copy of the original object. Unlike assignment, which only creates a reference to the original, a clone is a new instance with the same content. A deep clone duplicates the entire structure, including all nested properties. This is crucial when you want to modify a copy without affecting the original data.
1. Simple Cloning with JSON.stringify
A common way to clone objects is by using JSON.stringify()
together with JSON.parse()
.
This approach works by serializing the object into a JSON string and then parsing it back into a new object.
const original = { name: "Mario", info: { age: 30 } };
const copy = JSON.parse(JSON.stringify(original));
2. Issues with Cloning via JSON.stringify
This method has several important limitations:
- It doesn’t handle special types like
Date
,Map
,Set
,undefined
,Infinity
,NaN
, or functions. - Objects with circular references will throw an error during serialization.
- Custom class instances lose their methods and become plain objects.
const obj = { date: new Date(), greet: () => "hello" };
const clone = JSON.parse(JSON.stringify(obj));
console.log(clone.date instanceof Date); // false
console.log(clone.greet); // undefined
3. Deep Cloning with structuredClone()
To overcome the limitations of JSON.stringify
, modern JavaScript offers structuredClone()
,
a native function that performs a deep copy and correctly handles most data types.
const original = { name: "Mario", date: new Date(), numbers: [1, 2, 3] };
const copy = structuredClone(original);
3.1 Browser Compatibility for structuredClone()
Supported in:
- Chrome (from version 98)
- Firefox (from version 94)
- Safari (from version 15.4)
- Edge (from version 98)
3.2 Polyfill for structuredClone()
in Unsupported Browsers
A polyfill can simulate structuredClone()
in environments where it's not available.
One reliable method is to use the MessageChannel
interface.
What is MessageChannel
?
MessageChannel
is a Web API that enables asynchronous communication between two ports (or "channels").
When you send an object through a MessagePort
using postMessage
,
the browser automatically performs a structured clone of the data.
We can take advantage of this behavior to implement deep cloning.
function structuredClonePolyfill(obj) {
return new Promise((resolve, reject) => {
const { port1, port2 } = new MessageChannel();
port2.onmessage = (event) => resolve(event.data);
try {
port1.postMessage(obj);
} catch (err) {
reject(err);
}
});
}
Usage:
structuredClonePolyfill(obj).then((clone) => {
console.log(clone);
});
Note: this polyfill is asynchronous and requires a browser environment that supports MessageChannel
.
It won’t work in Node.js unless you use additional libraries.
Conclusion: Why Cloning Matters in Modern Programming
Cloning objects safely is critical in modern development practices, especially in immutable data handling like Redux or state management in front-end frameworks.
A deep clone ensures that changes do not unintentionally affect the original data, improving code predictability and maintainability.
Choosing between JSON.stringify
and structuredClone()
depends on your compatibility needs and the complexity of your objects.
Follow me #techelopment
Official site: www.techelopment.it
facebook: Techelopment
instagram: @techelopment
X: techelopment
Bluesky: @techelopment
telegram: @techelopment_channel
whatsapp: Techelopment
youtube: @techelopment