DEV Community

Cover image for Understand JavaScript Object References and Copying - Brief Explanation
Rinon Tendrinomena
Rinon Tendrinomena

Posted on

Understand JavaScript Object References and Copying - Brief Explanation

When working with objects in JavaScript, understanding the difference between object references and object copying is crucial. Here’s a detailed overview:


Object References

  1. Objects are reference types:
    • When you assign an object to a variable, you are assigning a reference to the memory location where the object is stored, not a copy of the object itself.
    • Modifying the object through one reference affects all references to the same object.
   let obj1 = { name: "Alice" };
   let obj2 = obj1; // obj2 now references the same object as obj1
   obj2.name = "Bob";
   console.log(obj1.name); // Output: "Bob"
Enter fullscreen mode Exit fullscreen mode
  1. Equality checks:
    • Two variables are equal if they reference the same object in memory, not if their contents are identical.
   let a = { key: "value" };
   let b = { key: "value" };
   console.log(a === b); // Output: false (different references)
   let c = a;
   console.log(a === c); // Output: true (same reference)
Enter fullscreen mode Exit fullscreen mode

Object Copying

There are two main types of object copying: shallow copy and deep copy.

1. Shallow Copy

  • A shallow copy creates a new object, but it only copies the first level of properties. Nested objects or arrays are still referenced, not duplicated.

Techniques for Shallow Copy:

  • Object.assign():

     let original = { name: "Alice", details: { age: 25 } };
     let copy = Object.assign({}, original);
     copy.details.age = 30;
     console.log(original.details.age); // Output: 30 (shared reference)
    
  • Spread operator (...):

     let original = { name: "Alice", details: { age: 25 } };
     let copy = { ...original };
     copy.details.age = 30;
     console.log(original.details.age); // Output: 30 (shared reference)
    
  • Both methods create a shallow copy, meaning nested objects are still linked.

2. Deep Copy

  • A deep copy duplicates the entire object, including nested structures. The new object is completely independent of the original.

Techniques for Deep Copy:

  • JSON.parse() and JSON.stringify():

     let original = { name: "Alice", details: { age: 25 } };
     let copy = JSON.parse(JSON.stringify(original));
     copy.details.age = 30;
     console.log(original.details.age); // Output: 25
    
    • Limitation: This method does not handle functions, undefined, Infinity, or special objects like Date or RegExp.
  • StructuredClone() (Modern JavaScript):

     let original = { name: "Alice", details: { age: 25 } };
     let copy = structuredClone(original);
     copy.details.age = 30;
     console.log(original.details.age); // Output: 25
    
    • This method handles most edge cases (e.g., circular references) but is not supported in older environments.
  • Custom Libraries:

    • Use libraries like lodash:
       import cloneDeep from "lodash/cloneDeep";
       let original = { name: "Alice", details: { age: 25 } };
       let copy = cloneDeep(original);
       copy.details.age = 30;
       console.log(original.details.age); // Output: 25
    

Summary Table

Action Result
Assignment (=) Creates a reference. Changes to one variable affect the other.
Shallow Copy Creates a new object but retains references for nested objects.
Deep Copy Creates a completely independent object, including nested structures.

Understanding these concepts helps you avoid unintended side effects when working with objects in JavaScript!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay