Back to all questions

How do you clone an object in JS?

Devs Hive

Devs Hive

Seen on interview: 6 users

This is an old chestnut that still comes up in interviews, usually at companies where people have clearly gotten stuck in their ways and missed a ton of JS updates. In general, there are three most common ways to clone an object in JavaScript.

Spread operator

This is the simplest and most elegant approach. The only catch is that spread performs a shallow clone. This means nested objects are not cloned and will still reference the original object.

const user = {
id: 1,
email: "test@test.com",
notifications: {
email: true
},
externalId: BigInt(232323345555),
};

const userClone = { ...user };

// Якщо ми змінимо значення поля user.notifications.email,
// то зміниться і userClone.notifications.email
// так як userClone.notifications не був склонований
// і фактично це просто посилання на user.notifications

user.notifications.email = false;

console.log(userClone.notifications.email); // false

JSON.stringify → JSON.parse

This is the good old-school method that makes a deep clone of an object. This means all nested objects get cloned. Overall, it works, but it has one problem: it only works with simple data types.

If the object has fields with Map/Set, undefined, Infinity, BigInt, etc., you will either get an error, or the fields will be lost or converted to a string. So using this approach in a real project is not the best idea, and it's better to use a third-party library or the approach I describe next.

const user = {
id: 1,
email: "test@test.com",
notifications: {
email: true
},
externalId: BigInt(232323345555),
};

// Так як externalId, це BigInt ми отримаємо помилку і клонування не відбудеться
const userClone = JSON.parse(JSON.stringify(user));

structuredClone

This is a relatively new method in JS that lets you make a deep clone, including of complex types that the previous method can't handle. It is well documented in MDN, so for a detailed breakdown, I recommend reading the documentation.

const user = {
id: 1,
email: "test@test.com",
notifications: {
email: true
},
externalId: BigInt(232323345555),
};

// Клонування буде успі
const user2 = structuredClone(user);


Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!