CKTIS / JavaScript
WeakMap: check, read, and write entries with has(), get(), and set()
Check whether a key is present, read its value, or update it. Learn to tell a missing entry from a stored `undefined` and know which keys a `WeakMap` accepts.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
weakMap.has(key)
weakMap.get(key)
weakMap.set(key, value)WeakMap.prototype.has/get/set is shorthand for three instance methods of WeakMap. Keys are matched by identity: two separate objects with identical properties are different keys.
has(key)returnstrueif an entry exists andfalseotherwise.get(key)returns the stored value, orundefinedif there is no entry. Usehas(key)to tell a missing entry from a storedundefined.set(key, value)adds an entry or replaces the value for the same key. It accepts any JavaScript value and returns the sameWeakMapinstance, so calls can be chained.
ECMAScript 2024 allows objects (including functions) and non-registered symbols as keys, such as Symbol() and Symbol.iterator, but not symbols from Symbol.for(). Older runtimes may accept only object keys; check symbol-key support in your target runtime.
For an invalid key such as 1, has() returns false, get() returns undefined, and set() throws TypeError. All three methods check this first: calling one with a this value that is not a genuine WeakMap instance throws TypeError regardless of the key.
Use WeakMap for per-object metadata without keeping the key alive, even if the stored value refers back to the key. Garbage collection has no guaranteed timing. WeakMap provides neither key iteration nor size; use Map if you need those features or want string or number keys.
Examples
{
const map = new WeakMap();
const key = { id: 1 };
const lookalike = { id: 1 };
map.set(key, undefined);
console.log(`stored: ${map.has(key)}, ${map.get(key)}`);
console.log(`missing: ${map.has(lookalike)}, ${map.get(lookalike)}`);
const result = map.set(key, 42);
console.log(`updated: ${map.get(key)}, same map: ${result === map}`);
console.log(`invalid key: ${map.has(1)}, ${map.get(1)}`);
try {
map.set(1, 42);
} catch (error) {
console.log(error.name);
}
}Result
stored: true, undefined missing: false, undefined updated: 42, same map: true invalid key: false, undefined TypeError
`key` and `lookalike` have the same `id` but are distinct objects. Both reads initially give `undefined`; only `has(key)` returns `true`. The second write replaces the value with `42` and returns the same map. The key `1` shows how reads and writes differ for an invalid key.
Related lessons
- JavaScript · Lesson 17 · Advanced · Version: 4