How to Create a Deep Copy of an Object in JavaScript?

Question

What are the steps to create a deep copy of an object in JavaScript while ensuring that the original and cloned objects do not share references?

// Example of deep copy using structuredClone
const originalObj = { a: 1, b: { c: 2 } };
const deepCopiedObj = structuredClone(originalObj);
console.log(deepCopiedObj.b === originalObj.b); // false

Answer

Creating a deep copy of an object involves duplicating an object and all its nested properties (if any) so that modifications to the clone do not affect the original object. This technique is important in programming, especially in JavaScript, where reference types can lead to unintended mutations. In this guide, we’ll explore several methods for achieving deep copies in JavaScript, ensuring that the original and the cloned objects do not share references.

// Deep copy using JSON methods
const original = { x: 1, y: { z: 2 } };
const clone = JSON.parse(JSON.stringify(original));
console.log(clone.y === original.y); // false

Causes

  • Direct assignment creates a reference, not a copy (e.g., `let clone = obj` does not create a new object).
  • Nested objects or arrays can lead to shared references, causing the deep copy to fail.

Solutions

  • Use JSON methods: `JSON.parse(JSON.stringify(obj))` (works for JSON-serializable objects).
  • Implement a recursive function to copy properties and nested structures.
  • Utilize built-in methods like `structuredClone(obj)`, which was introduced in recent JavaScript versions.

Common Mistakes

Mistake: Using shallow copy methods which do not copy nested objects.

Solution: Always use a method that recursively copies all properties.

Mistake: Assuming JSON methods can copy functions or special object types (e.g., Date).

Solution: Use `structuredClone` or a custom deep copy function to handle these types.

Helpers

  • deep copy JavaScript
  • clone object JavaScript
  • JavaScript object deep copy
  • copy nested objects JavaScript
  • structuredClone JavaScript

Related Questions

⦿What is the Difference Between StringUtils.isBlank() and String.isEmpty()?

Learn the key differences between StringUtils.isBlank from Apache Commons Lang and String.isEmpty from Java including their use cases and behavior.

⦿Understanding the Uses of Optional in Java 8

Explore the best practices for using Optional in Java 8 including public methods parameters beans and collections with clear examples.

⦿How to Stub a Mockito Method to Ignore Arguments

Learn how to stub a Mockito method to return a value without considering its argument. Effective techniques and examples provided.

⦿How to Capture User Input in Java: A Comprehensive Guide

Learn how to effectively capture user input in Java for your applications. Stepbystep guide with code examples and common mistakes.

⦿Unique Features of IntelliJ IDEA Compared to Eclipse

Discover the unique features and capabilities of IntelliJ IDEA that Eclipse lacks. Learn insights directly from exEclipse users.

⦿What is the Best Portable Method to Retrieve the Hostname in Java?

Discover the most efficient and portable way to obtain the hostname of the current machine in Java comparing different approaches like Runtime and InetAddress.

⦿How to Import a JAR File in Eclipse: A Step-by-Step Guide

Learn how to easily import a JAR file into your Eclipse project with this comprehensive guide. Stepbystep instructions included

⦿Resolving SSL Connection Warning When Connecting to MySQL Database

Learn how to fix the SSL connection warning while connecting to a MySQL database using Java JDBC. Solutions code examples and debugging tips included.

⦿How to Resolve the "No Enclosing Instance of Type Foo is Accessible" Error in Java?

Learn what causes the No enclosing instance of type Foo is accessible error in Java and how to fix it with clear examples and solutions.

⦿What Causes a `java.lang.ArrayIndexOutOfBoundsException` and How Can I Prevent It?

Learn about the causes of ArrayIndexOutOfBoundsException in Java and effective strategies to prevent this error in your code.

© Copyright 2025 - CodingTechRoom.com