Clone an Object in JavaScript


Have you ever wondered how to efficiently clone an object in JavaScript? If you’re just starting your coding journey, this is an essential concept to grasp. JavaScript objects can hold complex data, and sometimes, you need an exact copy—without affecting the original. This blog will guide you step-by-step on how to clone an object in JavaScript, using methods that cater to beginners. We’ll explain complex ideas in simple terms, provide practical examples, and show real-world applications. Ready to dive in and make your coding skills stronger? Let’s get started!

What is Object Cloning?

Object cloning in programming refers to creating a duplicate or copy of an existing object. This allows you to create a new instance with the same values or properties as the original object without altering the original data. Cloning can be shallow or deep:

  • Shallow cloning copies the object’s references, meaning changes to nested objects will affect both the original and the clone.
  • Deep cloning creates a completely independent copy, including nested objects, ensuring no shared references between the original and the clone.

In many programming languages, object cloning can be achieved using built-in methods or interfaces like clone() in Java or the copy module in Python. It’s useful for scenarios like creating backups or working with immutable objects.

Understanding Object Cloning in JavaScript

JavaScript Objects and Reference Types

In JavaScript, objects are stored as reference types. This means that when you assign an object to a variable, you’re storing a reference (or memory address) to that object rather than a copy of its value.

Example:

let obj1 = { name: "John", age: 30 };
let obj2 = obj1;

obj2.age = 35; 

console.log(obj1.age); // Output: 35 (both variables reference the same object)

Here, obj1 and obj2 point to the same object in memory, so modifying obj2 also affects obj1.

Shallow Copy vs. Deep Copy

When cloning an object, we need to consider whether we are making a shallow copy or a deep copy.

  1. Shallow Copy
    • Copies only the top-level properties of an object.If the object contains nested objects, only the references to those objects are copied, not their actual values.Changes to the nested object in the copy will affect the original.
    Example of Shallow Copy:
    let obj1 = { name: "Alice", details: { age: 25, city: "New York" } }; let obj2 = { ...obj1 }; // Spread operator creates a shallow copy obj2.details.age = 30; console.log(obj1.details.age); // Output: 30 (Nested object is still linked)
  2. Deep Copy
    • Creates a completely independent copy, including all nested objects.Changes to the deep copy will not affect the original object.Requires special methods like JSON.parse(JSON.stringify()) or structuredClone().
    Example of Deep Copy:
    let obj1 = { name: "Bob", details: { age: 40, city: "London" } }; let obj2 = JSON.parse(JSON.stringify(obj1)); // Deep copy obj2.details.age = 50; console.log(obj1.details.age); // Output: 40 (Original object remains unchanged)

Understanding these differences is crucial when working with JavaScript objects to avoid unintended side effects.

Methods for Cloning Objects in JavaScript

There are several ways to clone objects in JavaScript. The method you choose depends on whether you need a shallow copy or a deep copy.

1. Using Object.assign() (Shallow Copy)

Syntax and Usage

The Object.assign() method copies the enumerable own properties from one or more source objects to a target object.

let original = { name: "Alice", age: 25 };
let clone = Object.assign({}, original);

Example Demonstrating Shallow Cloning

let obj1 = { name: "Alice", details: { age: 25, city: "New York" } };
let obj2 = Object.assign({}, obj1);

obj2.details.age = 30;
console.log(obj1.details.age); // Output: 30 (Nested object is still referenced)

Limitations with Nested Objects

  • Object.assign() performs a shallow copy, meaning nested objects are still referenced.
  • Changes to a nested object in the clone will reflect in the original.

2. Using the Spread Operator (...) (Shallow Copy)

Syntax and Usage

The spread operator (...) is a simpler and more modern alternative to Object.assign().

let original = { name: "Alice", age: 25 };
let clone = { ...original };

Example Demonstrating Shallow Cloning

let obj1 = { name: "Alice", details: { age: 25, city: "New York" } };
let obj2 = { ...obj1 };

obj2.details.city = "Los Angeles";
console.log(obj1.details.city); // Output: "Los Angeles" (Nested object is still referenced)

Limitations with Nested Objects

  • Like Object.assign(), the spread operator only clones top-level properties.
  • Nested objects remain linked to the original.

3. Using JSON.parse(JSON.stringify()) (Deep Copy)

Syntax and Usage

This method first converts an object to a JSON string and then parses it back into an object, creating a completely independent deep copy.

let deepClone = JSON.parse(JSON.stringify(original));

Example Demonstrating Deep Cloning

let obj1 = { name: "Alice", details: { age: 25, city: "New York" } };
let obj2 = JSON.parse(JSON.stringify(obj1));

obj2.details.city = "Los Angeles";
console.log(obj1.details.city); // Output: "New York" (Original remains unchanged)

Limitations

  • Functions are lost: Since JSON doesn’t support functions, they will be removed.
  • undefined values are lost: Any property with undefined will be removed.
  • Symbol properties are lost: Symbols are not supported in JSON.

4. Using structuredClone() (Deep Copy)

Introduction to structuredClone()

The structuredClone() method is a modern way to create a deep copy of objects, preserving complex data types.

Example Demonstrating Deep Cloning

let obj1 = { name: "Alice", details: { age: 25, city: "New York" } };
let obj2 = structuredClone(obj1);

obj2.details.city = "Los Angeles";
console.log(obj1.details.city); // Output: "New York" (Original remains unchanged)

Advantages Over Other Methods

Preserves functions, undefined, and symbols (unlike JSON.parse()).
Handles complex objects like Maps, Sets, and Dates.
Native and faster than third-party libraries.
Not supported in older browsers (requires a polyfill for compatibility).

Which Method Should You Use?

MethodCopy TypeHandles Nested Objects?Preserves Functions & Symbols?
Object.assign()Shallow❌ No✅ Yes
Spread Operator (...)Shallow❌ No✅ Yes
JSON.parse(JSON.stringify())Deep✅ Yes❌ No
structuredClone()Deep✅ Yes✅ Yes

If you only need a shallow copy, use the spread operator or Object.assign().
For deep copies, structuredClone() is the best choice, unless you need support for older browsers.

Real-Life Uses of Cloning Objects in JavaScript

Welcome to the world of coding! Today, we’re diving into a fun yet critical topic: how to Clone an Object in JavaScript. As a beginner, you might wonder, “Why clone an object?” Let’s explore real-life scenarios that make cloning handy.


  1. Simplify Data Sharing: Imagine you’re working for a tech company that constantly shares data objects across multiple departments. The original object should remain unchanged. By cloning, each department gets its copy, allowing independent modifications without affecting the main dataset.

  2. Version Control in Gaming: In the gaming industry, saving various game states is vital for user experience. When a player makes a new move, cloning the object representing the game state ensures progress is saved separately. If a player decides to revert, they can effortlessly go back to a previous state without affecting the current game’s progress.

  3. Web App Personalization: Many brands seek to offer personalized experiences to each user. By cloning a template object and customizing it to match user preferences, apps can create unique user profiles. This allows seamless alteration of themes, preferences, and other personalized settings.

  4. E-commerce Transaction Processing: Retail platforms often need to process transactions where original order details should remain unchanged. By cloning an order object, developers can run tests and simulations without risking the integrity of live orders. Changes are made to cloned objects, allowing programmers to troubleshoot without disruption.

  5. Real-Time Applications: For apps like collaborative document editing, cloning lets users edit or draft content simultaneously. Clone an object in such apps, allowing multiple modifications without interference, ensuring everyone’s contributions integrate smoothly and correctly.

Cloning objects in JavaScript isn’t just a technique; it’s a bridge to writing clean, efficient, and reliable code. These practical uses prove its worth in the programming world!

Test Your Knowledge: Quiz on Cloning Objects in JavaScript!

  1. What is a shallow clone of an object?

    a) A complete duplicate of the original object
    b) A copy with identical reference pointers
    c) A copy creating new references for nested objects
  2. Which method is used for deep cloning an object?

    a) JSON.stringify() and JSON.parse()
    b) Object.assign()
    c) Spread operator (…)
  3. Which of the following will create a new object reference?

    a) Direct assignment
    b) JSON.parse(JSON.stringify(obj))
    c) Using var newObj = obj

  4. Can the spread operator clone nested objects?

    a) Yes, always
    b) Only in ES6
    c) No, it’s a shallow copy
  5. What does Object.assign() do when cloning an object?

    a) Creates a deep clone
    b) Copies all properties into the target object
    c) Ignores non-enumerable properties

Ready to check your answers and see if you’ve mastered how to Clone an Object in JavaScript? Give yourself a pat for every correct one, and don’t hesitate to explore the topic further if needed!

Our AI-powered js online compiler lets users instantly write, run, and test code, making learning JavaScript seamless. With AI assistance, coding becomes intuitive and efficient, helping users understand concepts faster while providing a friendly environment for beginners to experiment and grow.

Common Pitfalls and Best Practices in Object Cloning

1. Avoiding Unintended References in Cloned Objects

Pitfall: Using Object.assign() or the spread operator (...) for deep objects still maintains references to nested properties.
Best Practice: Use structuredClone() or JSON.parse(JSON.stringify()) to create a true deep copy.

let obj1 = { name: "Alice", details: { age: 25 } };
let obj2 = { ...obj1 }; // Shallow copy

obj2.details.age = 30;
console.log(obj1.details.age); // ❌ Output: 30 (unintended modification)

Solution: Use structuredClone()

let obj2 = structuredClone(obj1); 
obj2.details.age = 30;
console.log(obj1.details.age); // ✅ Output: 25 (original remains unchanged)

2. Handling Non-Enumerable Properties and Prototype Chains

Pitfall: Object.assign() and the spread operator do not copy non-enumerable properties or prototype methods.
Best Practice: Use Object.getOwnPropertyDescriptors() with Object.create() for cloning objects with prototype methods.

let obj1 = Object.create(
  { greet() { return "Hello"; } },
  { name: { value: "Alice", enumerable: true } }
);

let clone = Object.create(Object.getPrototypeOf(obj1), Object.getOwnPropertyDescriptors(obj1));
console.log(clone.greet()); // ✅ Output: "Hello"

3. Testing Cloned Objects to Ensure Integrity

Pitfall: Deep-cloning methods like JSON.parse(JSON.stringify()) strip functions, undefined, and symbols.
Best Practice: Always test clones, especially for objects containing functions, special data types, or circular references.

let obj1 = { fn: () => console.log("Hello"), symbol: Symbol("id") };
let obj2 = JSON.parse(JSON.stringify(obj1));

console.log(typeof obj2.fn); // ❌ Output: "undefined" (function lost)
console.log(obj2.symbol); // ❌ Output: undefined (symbol lost)

Solution: Use structuredClone()

let obj2 = structuredClone(obj1);
console.log(obj2.fn); // ✅ Function is preserved
console.log(obj2.symbol); // ✅ Symbol is preserved

Conclusion

In conclusion, learning to clone an object in JavaScript is an enlightening journey for any budding coder. Whether using simple loops or advanced methods like “Object.assign” and “spread operator”, mastering this skill opens many doors in programming. Check out Newtum for more insights. Keep exploring and coding!

Edited and Compiled by

This blog was compiled and edited by Rasika Deshpande, who has over 4 years of experience in content creation. She’s passionate about helping beginners understand technical topics in a more interactive way.

About The Author