WeakMap Basics and Key Restrictions
You'll learn: How to create WeakMaps and why they only accept objects as keys, not primitive values.
What is a WeakMap?
A WeakMap is a special collection similar to Map, but with strict limitations on what can be used as keys. While a regular Map accepts any value as a key (strings, numbers, objects, etc.), a WeakMap only accepts objects as keys. Primitive values like strings, numbers, or booleans will cause an error.
Think of it like a VIP club that only admits members with special ID cards (objects), not walk-ins with paper tickets (primitives).
Creating a WeakMap
const weakMap = new WeakMap();
The Object-Only Rule
const weakMap = new WeakMap();
const objKey = { id: 1 };
// ✅ Works: object as key
weakMap.set(objKey, 'some value');
// ❌ Throws TypeError: string is primitive
// weakMap.set('myKey', 'value');
// ❌ Throws TypeError: number is primitive
// weakMap.set(42, 'value');
Why Objects Only?
This restriction exists because WeakMap keys are "weakly held" (as you learned previously). The garbage collector can only track object references, not primitive values. Primitives are immutable and don't have the same reference-based identity that objects do, so they can't participate in the weak reference system.
Basic Operations
const weakMap = new WeakMap();
const key = { name: 'user' };
weakMap.set(key, 'data');
console.log(weakMap.get(key)); // 'data'
console.log(weakMap.has(key)); // true
weakMap.delete(key);
console.log(weakMap.has(key)); // false
Key Takeaway: WeakMaps only accept objects as keys because weak references require trackable object identities—primitives lack this property and would break the garbage collection mechanism.