CKTIS / JavaScript
WeakMap: read, write, and delete entries
Learn what `get`, `set`, and `delete` return, which keys a `WeakMap` accepts, and how to tell a missing entry from one whose stored value is `undefined`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const wm = new WeakMap();
wm.get(key);
wm.set(key, value);
wm.delete(key);WeakMap.prototype.get/set/delete refers to three separate prototype methods. Call them on a WeakMap instance, as in wm.get(key), not as static methods on the constructor. A detached call without a valid receiver, or a call with an incompatible this, throws TypeError.
wm.get(key) returns the stored value, or undefined if the key is absent or invalid. Use wm.has(key) to distinguish an absent entry from a stored undefined. wm.set(key, value) adds an entry or replaces its value. It accepts any value and returns the same instance, so you can chain calls. wm.delete(key) returns true if it removed an entry and false if the key is absent or invalid. It removes a map entry, not an object property as the delete operator does.
ECMAScript 2024 allows objects, including functions, and non-registered symbols such as those created by Symbol() as keys. Registered symbols from Symbol.for() and other primitives are invalid keys; set throws TypeError for them. Keys match by identity: two separate objects with the same properties are different keys. Check symbol-key support in your target runtime.
Use a WeakMap to associate metadata with an object without keeping that object alive merely because it is a key. The map does not hold its keys strongly. Garbage collection has no guaranteed timing, and keys cannot be enumerated. Use a Map if you need to iterate over keys.
Examples
{
const metadata = new WeakMap();
const item = { id: 1 };
console.log(metadata.set(item, 1) === metadata);
metadata.set(item, 2);
console.log(metadata.get(item));
console.log(metadata.get({ id: 1 }));
metadata.set(item, undefined);
console.log(metadata.get(item) === undefined && metadata.has(item));
console.log(metadata.delete(item));
console.log(metadata.delete(item));
console.log(metadata.get(item));
}Result
true 2 undefined true true false undefined
`set` returns the same map and replaces `1` with `2`. The fresh `{ id: 1 }` is a different key. `has` confirms that the entry storing `undefined` exists; only the first `delete` removes it.
Related lessons
- JavaScript · Lesson 3 · Advanced · Version: 4
- JavaScript · Lesson 7 · Advanced · Version: 4
- JavaScript · Lesson 41 · Intermediate · Version: 3