Arrays & Iterables
Sets & WeakSets
Master ES6 Sets and WeakSets. Understand uniqueness guarantees, constant time complexity operations, and garbage collection mechanisms in WeakSets.
1. Introduction
ES6 introduced two collections for storing unique values: Sets (storing unique primitive values and object references) and WeakSets (storing unique object references only, with weak garbage collection references).
2. Why It Matters
Using standard arrays to perform uniqueness checks requires scanning the entire array (O(N) time complexity). In contrast, Sets use hash-lookup tables under the hood to perform uniqueness checks in constant time (O(1) complexity).
3. Real-World Analogy
Think of a Guest Entry Log Book:
- Standard Set (VIP Access List): A guest book that only allows unique names. If Alice tries to sign in twice, the desk manager blocks the entry. Alice's name remains on the list permanently.
- WeakSet (Disposable Access Badge): Handing guests a temporary badge (object reference) to open doors. The building tracks the badge. If a guest loses their badge and walks away, the building cleanup crew discards the badge immediately (garbage collection), removing it from the tracking list automatically.
4. Sets
A Set is an ordered collection of unique values. Values are compared using SameValueZero comparison rules (where NaN is treated as equal to NaN).
5. WeakSets
A WeakSet is a collection of unique objects only. It has three key characteristics:
• Objects only: It cannot store primitive values (like strings or numbers).
• Weak references: If an object stored in a WeakSet has no other references pointing to it, it is garbage collected automatically.
• Not iterable: Because garbage collection is non-deterministic, WeakSets do not expose size, entries, or loop properties.
6. Comparison Summary
| Feature | Set | WeakSet |
|---|---|---|
| Allowed Data Types | Primitives & Objects | Objects only |
| Reference strength | Strong (prevents garbage collection) | Weak (allows garbage collection) |
| Iterability | Iterable (forEach, keys, size) | Not iterable (no size property) |
7. Practical Example
This script demonstrates deduplicating an array of values using a Set:
8. Common Mistakes
- Trying to store primitives in a WeakSet: Attempting to call
weakset.add('string')throws a TypeError. - Expecting objects with identical properties to be duplicates: Sets compare objects by reference, not value. Two separate object literals with identical properties are both stored as unique entries.
9. Quick Quiz
Q1: Which collection prevents memory leaks by allowing objects to be garbage collected when there are no other references to them?
A) Set
B) WeakSet
Answer: B — WeakSet stores weak references to objects, allowing them to be garbage collected when no longer used elsewhere.
10. Scenario-Based Challenge
The DOM Node Tracker:
You write a custom click counter tracker that registers click events on DOM nodes. If nodes are dynamically removed from the page, you want the tracker list to free their memory automatically to prevent memory leaks. Write a tracker constructor utilizing the correct Set type.
11. Debugging Exercise
Explain why this lookup returns false, and how to fix it:
const securityGroup = new Set(); securityGroup.add({ user: 'Alice', role: 'admin' });
// Verify access permissions console.log(securityGroup.has({ user: 'Alice', role: 'admin' })); // logs false! Why?
View Solution
Diagnosis: Sets compare objects by reference, not value. The object passed to has() is a new object literal with a different memory reference than the one stored in the Set.
Fix: Store the object reference in a variable, and pass that variable to both add() and has():
const alice = { user: 'Alice', role: 'admin' };
securityGroup.add(alice);
console.log(securityGroup.has(alice)); // true
12. Interview Questions
🟢 Q1: Why are WeakSets not iterable?
Answer: WeakSets are not iterable because their contents depend on the state of garbage collection, which is non-deterministic (it depends on browser memory levels and execution time). If WeakSets were iterable, their list contents would change unpredictably during execution, making loops unreliable.
13. Production Considerations
- • Memory Leak Prevention: Use
WeakSetwhen tracking associations on objects (like DOM elements or API nodes) that are dynamically created and destroyed. This prevents memory leaks by allowing the objects to be garbage collected automatically when they are no longer needed.