How to clone an object in JavaScript?

Babandeep Singh
Mar 10, 2023

In JavaScript, you can clone an object using several methods:

Object.assign() method: This method copies all enumerable properties of one or more source objects to a target object, and returns the target object. It is a shallow copy.

Spread Operator: The spread operator allows you to spread the properties of an object into a new object. It is also a shallow copy.

JSON.parse() and JSON.stringify() methods: This method creates a deep copy of an object, but it has some limitations. It cannot clone functions or properties that have undefined or NaN values.

Note that when cloning an object, if the object contains nested objects or arrays, those objects and arrays are not cloned recursively. To make a deep clone of an object with nested objects and arrays, you will need to use a more sophisticated cloning technique.

--

--