13 May 2017

Whether you're using vanilla JavaScript or popular frameworks like React, the ability to create deep copies of objects proves invaluable. Take control of your data structures, sidestepping unintended references, and ensuring independence between original and cloned objects. For an example, when managing state, it's crucial to clone objects to avoid unintended side effects and data errors. One common scenario where cloning is necessary is when updating state that is an object or an array. This is particularly relevant when using setState to modify the state in a component.

Source code viewer
  1. // Original object
  2. const originalObject = {
  3. name: 'John Doe',
  4. age: 25,
  5. hobbies: ['programming', 'construction', 'trading']
  6. };
  7.  
  8. // Using structuredClone to create a deep copy
  9. const clonedObject = structuredClone(originalObject);
  10.  
  11. // Modifying the cloned object
  12. clonedObject.name = 'Jane Doe';
  13. clonedObject.hobbies.push('investing');
  14.  
  15. // Logging the original and cloned objects
  16. console.log('Original Object:', originalObject);
  17. console.log('Cloned Object:', clonedObject);
Programming Language: ECMAScript