Object metadata
Attach cached or computed metadata to objects without extending their lifetime.
JS Puzzles · Const
WeakMap associates values with object keys without preventing those keys from being garbage-collected. Its entries cannot be enumerated, and cleanup timing is controlled by the JavaScript engine.
A WeakMap stores values under object keys without strongly retaining those keys. When a key has no other references, the engine may collect the key and its associated value; cleanup timing is implementation-dependent, and the collection cannot be enumerated.
new WeakMap(); weakMap.set(key, value); weakMap.get(key); weakMap.has(key); weakMap.delete(key)| Name | Type | Description |
|---|---|---|
key | object | The object used as the weak key. |
value | any | The value associated with the key; it may be any JavaScript value. |
WeakMap methods return the associated value, a boolean for has/delete, or the WeakMap instance for set; the page specifically lists get, set, delete, and has.
const metadata = new WeakMap();
let user = { name: "John" };
metadata.set(user, { lastLogin: new Date() });
console.log(metadata.get(user));
user = null; // The object and associated metadata may be collected later.The metadata is associated with the object without keeping that object alive.
Attach cached or computed metadata to objects without extending their lifetime.
Store auxiliary data for objects managed by another collection or subsystem.
Avoid memory retention when associated objects become unreachable.
MapWeakSetgarbage collectionweak references