Skip to main content
InterviewHubPRO
Section Overview
Q209

Question 209 of 536

Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

39%
JavaScript & V8 Internals (536 Qs)•Part 4: Prototypes, Object Methods & Event Loop (174 - 253)

What are the differences between WeakSet and Set

junior LevelMost AskedCode ExampleEvent LoopPrototypes

The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. i.e, An object in WeakSet can be garbage collected if there is no other reference to it. Other differences are:

  1. Set can store any value whereas WeakSet can store only collections of objects
  2. WeakSet does not have size property unlike Set
  3. WeakSet does not have methods such as clear, keys, values, entries, forEach.
  4. WeakSet is not iterable.

Practical Code Example

javascript
// WeakSet vs Set:
// 1. WeakSet only holds OBJECT references (no primitives)
// 2. Objects are held weakly (garbage collected if no other references exist)
// 3. WeakSet is NOT iterable and has no .size property:

const visited = new WeakSet();
let node = { id: 'dom-node-1' };
visited.add(node);
console.log(visited.has(node)); // true

node = null; // Object is automatically cleaned up by garbage collection!