WeakMap. 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

WeakMap is a special version of Map that holds keys “weakly”. This means that if the key object is no longer used anywhere else, the garbage collector can remove it along with its value from WeakMap. Keys can only be objects.

const weakMap = new WeakMap();
const obj = {};
 
weakMap.set(obj, 'value');
console.log(weakMap.get(obj)); // 'value'
 
// Can't iterate!
// for (const [key, value] of weakMap) // Error!

Full Answer

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

WeakMap Features

Main WeakMap features:

Simple Examples

Creation and Basic Methods

// Creating WeakMap
const privateData = new WeakMap();
 
// Objects as keys
const user1 = { name: 'John' };
const user2 = { name: 'Peter' };
 
// Adding data
privateData.set(user1, { password: '123' });
privateData.set(user2, { password: '456' });
 
// Getting data
console.log(privateData.get(user1)); // { password: '123' }
 
// Checking existence
console.log(privateData.has(user1)); // true
 
// Deletion
privateData.delete(user1);
console.log(privateData.has(user1)); // false

Automatic Cleanup

let obj = {};
const weakMap = new WeakMap();
 
weakMap.set(obj, 'data');
 
// When obj is no longer used
obj = null;
 
// Object and its data will be automatically removed
// by garbage collector (at some point)

WeakMap Properties and Methods

Basic Methods

const weakMap = new WeakMap();
const key = {};
 
// set(key, value) — adds key-value pair
weakMap.set(key, 'value');
 
// get(key) — gets value by key
const value = weakMap.get(key);
 
// has(key) — checks key existence
const exists = weakMap.has(key);
 
// delete(key) — removes element by key
weakMap.delete(key);
 
// NO size property!
// NO clear() method!

Why You Can’t Iterate WeakMap

No Iteration!

const weakMap = new WeakMap();
const obj = {};
 
weakMap.set(obj, 'value');
 
// ❌ Error — can't iterate WeakMap
// for (const [key, value] of weakMap) // TypeError!
 
// ❌ Error — no keys(), values(), entries() methods
// weakMap.keys(); // TypeError!
 
// ❌ Error — no forEach
// weakMap.forEach(); // TypeError!

When to Use WeakMap

For Private Data

const privateData = new WeakMap();
 
class User {
  constructor(name) {
    this.name = name;
    // Private data not visible from outside
    privateData.set(this, { password: 'secret' });
  }
  
  getPassword() {
    return privateData.get(this).password;
  }
}

For Caching with Automatic Cleanup

const cache = new WeakMap();
 
function processData(obj) {
  if (cache.has(obj)) {
    return cache.get(obj); // from cache
  }
  
  const result = heavyCalculation(obj);
  cache.set(obj, result); // to cache
  return result;
}
 
// When obj object is no longer needed,
// cache will automatically clear

Common Mistakes

Trying to Use Primitives as Keys

// ❌ Error — only objects as keys
const weakMap = new WeakMap();
// weakMap.set('string', 'value'); // TypeError!
// weakMap.set(123, 'value'); // TypeError!
 
// ✅ Correctly — only objects
const obj = {};
weakMap.set(obj, 'value'); // works

Expecting Iteration

// ❌ Error — thinking WeakMap is like Map
const weakMap = new WeakMap();
const obj = {};
 
weakMap.set(obj, 'value');
 
// Can't iterate!
// weakMap.forEach((value, key) => {}); // Error!

Simple Rules

  1. Objects only — keys can only be 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. Privacy — convenient for storing private data 🔐

WeakMap is an excellent tool for storing data related to objects without risk of memory leaks! 💪


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