How to clone anything in JavaScript

Iman RoustaIman Rousta
1 min read

The global structuredClone() can be used to create a deep copy of a given value.

Example

In this example, we clone an object. After cloning, changes to each object do not affect the other object.

const fruits = {
  citrus: ["orange", "grapefruit", "lime"],
};

const clonedFruits = structuredClone(fruits);

clonedFruits.citrus.push("mandarin");
fruits.citrus.pop();

console.log(clonedFruits.citrus); 
// ["orange", "grapefruit", "lime","mandarin" ]
console.log(fruits.citrus); 
// ["orange", "grapefruit"]

Just remember that the structuredClone() method is a very recent API (For example, Chrome >= 98 and Firefox >= 94 are compatible with it). If you use it in the browser, make sure you use a build tool that provides core-js polyfills (e.g. babel).

1
Subscribe to my newsletter

Read articles from Iman Rousta directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Iman Rousta
Iman Rousta

Front-end developer