Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

WeakMap.get() — read a value by key

`weakMap.get(key)` returns the value stored for a key. Use `has(key)` to tell a missing entry apart from one whose value is `undefined`.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

weakMap.get(key)

WeakMap.get is shorthand for the instance method WeakMap.prototype.get, not a static method on the constructor. Call weakMap.get(key) to read the stored value without changing the map. Keys match by identity: two separately created objects with identical properties are different keys. If the stored value is an object, get() returns that same object, not a copy.

A missing entry and an entry storing undefined both produce undefined. Use weakMap.has(key) to distinguish them: it returns true when the entry exists, even if its value is undefined.

ECMAScript 2024 allows objects, including functions, and non-registered symbols such as Symbol('id') as keys. Older engines may support WeakMap but not symbol keys. On a WeakMap instance, get() returns undefined for an invalid key, such as a string or a symbol returned by Symbol.for(), whereas set() throws a TypeError. get() itself throws a TypeError if its this is not a WeakMap instance, for example when you call the detached method without binding it to an instance.

The map alone does not keep a key alive. When a key is no longer reachable, its entry can be removed during garbage collection. You cannot enumerate the keys or rely on an entry being removed at a particular time.

Examples

const weakMap = new WeakMap();
const key = { id: 1 };
const otherKey = { id: 1 };

weakMap.set(key, 42);
console.log(String(weakMap.get(key)));
console.log(String(weakMap.get(otherKey)));

weakMap.set(otherKey, undefined);
console.log(String(weakMap.get(otherKey)));
console.log(String(weakMap.has(otherKey)));
console.log(String(weakMap.get('id')));

Result

42
undefined
undefined
true
undefined

`key` and `otherKey` are distinct objects despite having identical properties. Both lookups of `otherKey` return `undefined`: first the entry is missing, then it exists with the value `undefined`, as `has()` confirms. The last lookup uses an invalid key.

Related lessons

  • JavaScript · Lesson 18 · Basic · Version: 4

Sources