In JavaScript, a Set stores object values by reference, not by copy.
This means changes made to an object are reflected everywhere that object is used, including inside a Set.
This behavior is important when working with real data like users, products, or configuration objects.
What Does Reference Mean in a Set?
When you add:
-
Primitive values (number, string, boolean) → stored by value
-
Objects and arrays → stored by reference
Two objects with the same content are still considered different if their references are different.
Reference Behavior with Objects
Output:
[{ name: "Book", price: 250 }]
Explanation:
-
The Set does not store a copy
-
It stores a reference to the same object
-
Updating the object updates the value inside the Set
Same Content, Different References
Explanation:
-
Even though content looks identical
-
obj1andobj2are different memory references -
So both are stored separately
Reference with Arrays
let list = [1, 2, 3];
set.add(list);
list.push(4);
console.log([...set]);
Output:
[[1, 2, 3, 4]]
Explanation:
-
Arrays are also objects
-
Set holds the reference, not a copy
-
Any update affects the stored value
Why Set Reference Matters
Understanding Set reference behavior helps you:
-
Avoid unexpected data changes
-
Manage shared objects safely
-
Debug data mutation issues
-
Build reliable applications
-
Work confidently with complex data structures
Quick Summary
-
Objects in Sets are stored by reference
-
Changes to the object affect the Set
-
Same-looking objects can still be treated as different
-
Primitives behave differently than objects
-
Important for real-world data handling
Conclusion
Set reference in JavaScript explains how Sets handle objects internally.
Once you understand reference behavior, you can avoid bugs, manage shared data properly, and write more predictable JavaScript code.