WeakMap in JavaScript
A WeakMap is a collection of key-value pairs where:
- Keys must be objects (no primitives like strings or numbers).
- Values can be any type.
- Keys are weakly referenced, meaning if there are no other references to the key object, it can be garbage-collected.
- Not iterable — you cannot loop over WeakMap entries.
- No
.size
property or methods to list keys/values.
WeakMap is useful for storing private data or temporary metadata associated with objects.
1. Creating a WeakMap
const weakMap = new WeakMap();
const obj1 = {};
const obj2 = {};
weakMap.set(obj1, "Alice");
weakMap.set(obj2, "Bob");
console.log(weakMap.has(obj1)); // true
console.log(weakMap.get(obj2)); // "Bob"
2. WeakMap Methods
A WeakMap has four methods for managing key-value pairs (keys must be objects, held weakly):
a. set(key, value)
Adds or updates a key-value pair.
const weakMap = new WeakMap();
const user = { name: "John" };
weakMap.set(user, { age: 30 });
b. get(key)
Returns the value associated with the key, or undefined
if not present.
console.log(weakMap.get(user)); // { age: 30 }
c. has(key)
Checks if a key exists in the WeakMap.
console.log(weakMap.has(user)); // true
d. delete(key)
Removes a key-value pair. Returns true
if the key existed and was removed.
weakMap.delete(user);
console.log(weakMap.has(user)); // false
3. Key Characteristics
Feature | WeakMap |
---|---|
Keys | Objects only |
Values | Any type |
Reference Type | Weak reference for keys (GC) |
Iterable | No |
Size property | No |
Garbage Collection | Automatic for keys with no references |
4. Practical Use Cases
a. Private Object Data
- Private data is not accessible outside the class.
- WeakMap allows automatic cleanup when
john
is garbage-collected.
const privateData = new WeakMap();
class User {
constructor(name) {
privateData.set(this, { secret: `Password for ${name}` });
}
getSecret() {
return privateData.get(this).secret;
}
}
const john = new User("John");
console.log(john.getSecret()); // Password for John
b. DOM Metadata Tracking
The data is automatically removed if div
is removed from the DOM and no other references exist.
const elementData = new WeakMap();
const div = document.createElement("div");
elementData.set(div, { clicked: false });
div.addEventListener("click", () => {
elementData.get(div).clicked = true;
});
5. Limitations
- Cannot iterate (no
for...of
or.keys()
). - Cannot get size of the WeakMap.
- Only object keys are allowed.
- Not suitable if you need to enumerate entries.
6. Comparison with Map
Feature | Map | WeakMap |
---|---|---|
Key Types | Any type | Objects only |
Garbage Collection | Strong references | Weak references (GC) |
Iterable | Yes | No |
Size | .size available | Not available |
Use Case | General-purpose | Private/temporary data |