WeakSet. What's special about it? What properties and methods does it have? How to iterate?

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

Brief Answer

WeakSet is a special version of Set that holds objects “weakly”. This means that if an object is no longer used anywhere else, the garbage collector can remove it from WeakSet. Stores only objects, and elements cannot be iterated.

const weakSet = new WeakSet();
const obj = {};
 
weakSet.add(obj);
console.log(weakSet.has(obj)); // true
 
// Can't iterate!
// for (const item of weakSet) // Error!

Full Answer

WeakSet is like a magical bag that cleans itself when things inside are no longer needed by anyone! If you put something in the bag, but nobody remembers that item anymore, the bag will throw it out by itself. This helps avoid memory leaks! 🧙

WeakSet Features

Main WeakSet features:

Simple Examples

Creation and Basic Methods

// Creating WeakSet
const trackedObjects = new WeakSet();
 
// Objects only
const obj1 = { name: 'first' };
const obj2 = { name: 'second' };
 
// Adding objects
trackedObjects.add(obj1);
trackedObjects.add(obj2);
 
// Checking existence
console.log(trackedObjects.has(obj1)); // true
console.log(trackedObjects.has(obj2)); // true
 
// Deletion
trackedObjects.delete(obj1);
console.log(trackedObjects.has(obj1)); // false

Automatic Cleanup

let obj = {};
const weakSet = new WeakSet();
 
weakSet.add(obj);
 
// When obj is no longer used
obj = null;
 
// Object will be automatically removed
// by garbage collector (at some point)

WeakSet Properties and Methods

Basic Methods

const weakSet = new WeakSet();
const obj = {};
 
// add(value) — adds object
weakSet.add(obj);
 
// has(value) — checks object existence
const exists = weakSet.has(obj);
 
// delete(value) — removes object
weakSet.delete(obj);
 
// NO size property!
// NO clear() method!

Why You Can’t Iterate WeakSet

No Iteration!

const weakSet = new WeakSet();
const obj = {};
 
weakSet.add(obj);
 
// ❌ Error — can't iterate WeakSet
// for (const item of weakSet) // TypeError!
 
// ❌ Error — no keys(), values(), entries() methods
// weakSet.keys(); // TypeError!
 
// ❌ Error — no forEach
// weakSet.forEach(); // TypeError!

When to Use WeakSet

For Tracking Objects

const processedObjects = new WeakSet();
 
function processObject(obj) {
  // Check if already processed
  if (processedObjects.has(obj)) {
    return 'already processed';
  }
  
  // Process object
  // ... processing logic ...
  
  // Mark as processed
  processedObjects.add(obj);
  return 'processed';
}

For Preventing Repeated Processing

const visitedNodes = new WeakSet();
 
function traverse(node) {
  // Don't process already visited nodes
  if (visitedNodes.has(node)) {
    return;
  }
  
  // Mark as visited
  visitedNodes.add(node);
  
  // Process node
  console.log('Processing:', node);
  
  // Recursively process child nodes
  if (node.children) {
    node.children.forEach(traverse);
  }
}

Common Mistakes

Trying to Add Primitives

// ❌ Error — objects only
const weakSet = new WeakSet();
// weakSet.add('string'); // TypeError!
// weakSet.add(123); // TypeError!
// weakSet.add(true); // TypeError!
 
// ✅ Correctly — objects only
const obj = {};
weakSet.add(obj); // works

Expecting Iteration

// ❌ Error — thinking WeakSet is like Set
const weakSet = new WeakSet();
const obj = {};
 
weakSet.add(obj);
 
// Can't iterate!
// weakSet.forEach(item => {}); // Error!

Regular Set vs WeakSet

// Regular Set vs WeakSet
const set = new Set(); // Can store any values
const weakSet = new WeakSet(); // Only objects
 
set.add("string"); // ✅ Works
// weakSet.add("string"); // ❌ Error!

Simple Rules

  1. Objects only — stores only objects 🗝️
  2. Weak references — objects are automatically removed by garbage collector 🗑️
  3. No iteration — can’t iterate, no keys(), values(), entries() methods 🚫
  4. No size — no property to get element count 🚫
  5. Tracking — convenient for tracking objects 🔍

WeakSet is an excellent tool for tracking objects without risk of memory leaks! 💪


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