Tags: 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.
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:
originalObj
and newObj
reference the same object in memory. When you modify the age
property using newObj
, the change is reflected in originalObj
as well, because both variables point to the same memory location.If you want to create a copy of an object without affecting the original, you might consider using the spread operator ...
:
Explanation:
originalObj
and newObj
are separate objects. Changing newObj
does not affect originalObj
.However, since the copy is shallow, nested objects within the original object are still shared between the original and the copied object:
Explanation:
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:
structuredClone
method ensures that newObj
is a completely independent copy of originalObj
, with no shared references.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 (e.g., int
, float
, char
) store their values directly. When you assign one primitive variable to another, the value is copied:
Explanation:
a
and b
are independent of each other after the assignment.Reference types in Java (e.g., objects, arrays) work similarly to JavaScript objects. They store a reference to the actual data in memory:
Explanation:
list1
and list2
reference the same ArrayList object in memory. Changes made through list2
are reflected when accessing list1
.