CKTIS / JavaScript
WeakMap — metadata with weakly held keys
WeakMap associates values with keys without keeping the keys themselves alive. Learn set, get, has, and delete, identity-based key comparison, and the limitations around iteration and garbage collection.
Version: ECMAScript 2015 (ES2015) introduced WeakMap. ECMAScript 2023 (ES2023) added support for non-registered symbols as keys.
Syntax
const wm = new WeakMap();
wm.set(key, value);
wm.get(key);
wm.has(key);
wm.delete(key);WeakMap stores key–value associations. Keys can be objects or symbols outside the global symbol registry, such as Symbol(), but not Symbol.for(). Support for these symbols is part of ECMAScript 2023; older engines may accept only objects. Values can be any JavaScript value. Objects are compared by identity: two separate {} objects are different keys.
WeakMap.set here means the instance method WeakMap.prototype.set, not a static method. wm.set(key, value) adds or replaces a value and returns wm. Likewise, WeakMap.get means WeakMap.prototype.get: wm.get(key) returns the value or undefined. WeakMap.prototype.has, called as wm.has(key), distinguishes a missing entry from an entry whose value is undefined.
WeakMap.delete means WeakMap.prototype.delete: wm.delete(key) removes the entry and returns true if it existed, or false otherwise. An invalid key type causes TypeError in set; for that key, get returns undefined, while has and delete return false.
The weak association does not prevent collection of a key that is otherwise unreachable. Collection timing is not guaranteed; do not make program correctness depend on it. WeakMap provides neither entry iteration nor size. Use it for object-associated metadata; choose Map when you need to enumerate entries.
Examples
const metadata = new WeakMap();
const key = {};
const other = {};
console.log(metadata.set(key, 7) === metadata);
console.log(metadata.get(key));
console.log(metadata.has(other));
metadata.set(key, undefined);
console.log(metadata.has(key));
console.log(metadata.get(key) === undefined);
console.log(metadata.delete(key));
console.log(metadata.delete(key));Result
true 7 false true true true false
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.
Sources
- ECMAScript® Language Specification
- ECMAScript® Language Specification — Keyed Collections
- ECMAScript® 2023 Language Specification — Executable Code and Execution Contexts
- Official reference — tc39.es: ecma262
- Official reference — tc39.es: ecma262
- Official reference — tc39.es: ecma262
- Official reference — developer.mozilla.org: WeakMap / has