life is too short for a diary




Understanding Object References in JavaScript

Tags: javascript

Author
Written by: Tushar Sharma
Featured image for Understanding Object References in JavaScript

When working with JavaScript, it's important to understand that objects are reference types. This means that when you assign an object to a new variable, you're not creating a new copy of the object—instead, both variables reference the same object in memory. This can lead to some unexpected behavior if you're not careful.

JavaScript Object References

Let's start with a simple example:

In this case, x and y are primitive types (numbers), changing it doesn't change value since it's copied to different memory location.

However, objects in JavaScript work differently:

Explanation:

Shallow Copy with the Spread Operator

If you want to create a copy of an object without affecting the original, you might consider using the spread operator ...:

Explanation:

However, since the copy is shallow, nested objects within the original object are still shared between the original and the copied object:

Explanation:

Deep Copy with structuredClone

To avoid the pitfalls of shallow copying, you can use structuredClone, which creates a deep copy of the object, including all nested objects:

Explanation:

Comparing JavaScript with Java

The concept of references in JavaScript is similar to how Java handles data types, particularly when comparing primitive types and reference types.

Primitive Types in Java

Primitive types in Java (e.g., int, float, char) store their values directly. When you assign one primitive variable to another, the value is copied:

Explanation:

Reference Types in Java

Reference types in Java (e.g., objects, arrays) work similarly to JavaScript objects. They store a reference to the actual data in memory:

Explanation:


comments powered by Disqus