What's the difference between Set and WeakSet?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Hard
#JavaScript #Collections #JS Basics

Brief Answer

Set and WeakSet are both collections for storing unique values, but they have important differences:

  1. Set can store any values (strings, numbers, objects), while WeakSet only stores objects 📦
  2. Set can be iterated, but WeakSet cannot 🔍
  3. WeakSet automatically removes objects that are no longer used anywhere else 🗑️
// Set — stores any values
const set = new Set([1, 2, 'hello', {}]);
 
// WeakSet — only objects
const obj = {};
const weakSet = new WeakSet([obj]);

Full Answer

Think of Set as a regular box where you can put anything: toys, books, clothes. And WeakSet is a magical box that throws away things when no one needs them anymore! 📦✨

Main Differences

Value Types

// Set can store anything
const set = new Set();
set.add(1);        // number ✅
set.add('text');   // string ✅
set.add({});       // object ✅
 
// WeakSet only objects
const weakSet = new WeakSet();
// weakSet.add(1);     // ❌ Error!
// weakSet.add('text'); // ❌ Error!
weakSet.add({});       // ✅ Only objects

Iterating Elements

const set = new Set([1, 2, 3]);
 
// Set can be iterated
for (const item of set) {
  console.log(item); // 1, 2, 3
}
 
const weakSet = new WeakSet([{a: 1}, {b: 2}]);
 
// ❌ WeakSet cannot be iterated!
// for (const item of weakSet) // Error!

How WeakSet Works

WeakSet is like a friend who only remembers people you’re still in touch with. If a person has left your life (no one holds a reference to them anymore), WeakSet forgets them automatically! 🧠

Automatic Cleanup

let obj = { name: 'John' };
const weakSet = new WeakSet([obj]);
 
// When obj is no longer used by anyone
obj = null;
 
// Object will be automatically removed from WeakSet
// Garbage collector takes care of it 🗑️

When to Use Set

For Storing Any Unique Values

// Unique users
const uniqueUsers = new Set();
 
// Unique tags
const tags = new Set(['js', 'css', 'html', 'js']); 
// Will only have ['js', 'css', 'html']

When Iteration is Needed

// Need to go through all elements
const numbers = new Set([1, 2, 3]);
 
numbers.forEach(num => {
  console.log(num); // 1, 2, 3
});

When to Use WeakSet

For Tracking Objects

// Track already processed objects
const processed = new WeakSet();
 
function process(obj) {
  if (processed.has(obj)) {
    return 'already processed';
  }
  
  processed.add(obj);
  return 'processed';
}

For Preventing Repeated Processing

// Check if we've already processed this node
const visited = new WeakSet();
 
function traverse(node) {
  if (visited.has(node)) {
    return; // Already been here
  }
  
  visited.add(node);
  // Process node...
}

Common Mistakes

Trying to Store Primitives in WeakSet

// ❌ Error!
const weakSet = new WeakSet();
// weakSet.add('string'); // TypeError!
// weakSet.add(123);      // TypeError!
 
// ✅ Correct
const obj = {};
weakSet.add(obj); // Only objects!

Expecting to Iterate WeakSet

// ❌ Cannot iterate WeakSet
const weakSet = new WeakSet([{a: 1}]);
// weakSet.forEach(item => {}); // Error!

Simple Rules

  1. Set — universal box for any values 📦
  2. WeakSet — magical box only for objects 🧙
  3. Set can be iterated, WeakSet — cannot 🔍
  4. WeakSet cleans itself, Set — doesn’t 🗑️
  5. Use Set for general tasks, WeakSet for tracking objects 🎯

Understanding the difference between Set and WeakSet helps choose the right tool for the job and avoid memory issues! 💪


Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪