How to clone anything in JavaScript

How to clone anything in JavaScript

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).