CKTIS / JavaScript
WeakMap.prototype.has(): Check whether a key is present
`weakMap.has(key)` checks whether the map contains an entry for that key, even if the stored value is `undefined`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
weakMap.has(key)WeakMap.prototype.has is an instance method, not a static method. Calling weakMap.has(key) returns true if that map contains an entry for the key and false otherwise. It does not change the map. Keys are matched by identity: two separate objects with the same properties are different keys.
Use has() to tell a missing entry apart from an entry whose value is undefined. In both cases, get() returns undefined.
ECMAScript 2024 permits objects (including functions) and non-registered symbols such as Symbol('id') as keys. Older runtimes may support only object keys. For an invalid key, such as a string or a symbol from Symbol.for('id'), has() returns false, whereas set() throws a TypeError.
An invalid this is different: the method requires a WeakMap instance as this. So const has = weakMap.has; has(key); throws a TypeError rather than returning false.
An entry in a WeakMap does not by itself keep its key from being garbage-collected. has() requires you to supply the key; it cannot list keys or tell you when garbage collection happened.
Examples
{
const weakMap = new WeakMap();
const key = { id: 1 };
const otherKey = { id: 1 };
weakMap.set(key, undefined);
console.log(weakMap.has(key));
console.log(weakMap.get(key));
console.log(weakMap.has(otherKey));
console.log(weakMap.get(otherKey));
console.log(weakMap.has("id"));
}Result
true undefined false undefined false
Both `get()` calls return `undefined`, but only `has(key)` returns `true`. `otherKey` has the same properties but is a different object, and the string `"id"` is not a valid key.
Related lessons
- JavaScript · Lesson 10 · Intermediate · Version: 3