Lesson 83 - WeakMaps in JavaScript
What is a WeakMap?
A WeakMap is similar to a Map but with some differences that make it more suitable for storing data tied to object lifecycles. Keys in a WeakMap must be objects, and they are held "weakly," meaning if there are no other references to the object, it can be garbage collected.
Key Differences from Map
Feature | Map |
WeakMap |
---|---|---|
Key types | Any | Only objects |
Iterability | Yes | No |
Size property | Yes (.size ) |
No |
Garbage Collection safe | No | Yes (weakly held references) |
Creating a WeakMap
const weakMap = new WeakMap();
let user = { name: "Jane" };
weakMap.set(user, "Active");
console.log(weakMap.get(user)); // Active
Note: If the
user
object is no longer referenced elsewhere, it will be garbage collected, and the WeakMap entry will disappear automatically.
Valid Usage
const wm = new WeakMap();
const obj1 = {};
const obj2 = {};
wm.set(obj1, "Data for obj1");
wm.set(obj2, "Data for obj2");
console.log(wm.has(obj1)); // true
wm.delete(obj2); // removes obj2 from the WeakMap
Invalid Usage
const wm = new WeakMap();
wm.set("name", "Lance"); // Error: keys must be objects
Use Cases
- Private data for class instances
- Caching or memoization tied to object references
- Event listeners or DOM nodes storage without memory leaks
Try Your Hand
- Create a WeakMap and store some metadata related to a user object.
- Use
get()
to retrieve the data. - Check if the key exists using
has()
. - Delete the key from the WeakMap.