How to clone an object in JavaScript

Cloning objects is crucial when you need to create copies without affecting the original object, especially in state management and functional programming. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented object cloning countless times in component state handling and data manipulation. From my expertise, the most modern and clean approach is using the spread operator for shallow cloning. This method is concise, readable, and well-supported across all modern browsers.

Use the spread operator to create a shallow copy of an object.

const original = { name: 'John', age: 30 }
const cloned = { ...original }

Here the spread operator ... expands all enumerable properties from the original object into a new object literal. This creates a new object with the same properties but different reference, so modifying the cloned object won’t affect the original. This only creates a shallow copy, meaning nested objects are still referenced.

Best Practice Note:

For deep cloning with nested objects, use structuredClone() in modern browsers or a utility library. This is the same approach we use in CoreUI components for safe state updates and preventing unwanted mutations.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Remove the Last Character from a String in JavaScript
How to Remove the Last Character from a String in JavaScript

How to compare dates with JavaScript
How to compare dates with JavaScript

How to Clone an Object in JavaScript
How to Clone an Object in JavaScript

How to sleep in Javascript
How to sleep in Javascript

Answers by CoreUI Core Team