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.