Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

WeakMap.prototype.get() — read a value by key

Use `weakMap.get(key)` to read a stored value without changing the map. Use `has()` 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.prototype.get is an instance method you call as weakMap.get(key). It returns the value associated with the key without adding or changing an entry. If the stored value is an object, you get the same object back, not a copy.

Keys are matched by identity: two separate objects with identical properties are different keys. ECMAScript 2024 allows objects and non-registered symbols as keys, such as symbols created with Symbol() but not Symbol.for(). Older runtimes may not support symbol keys.

get() returns undefined if the entry is missing, the key is invalid (for example, a string), or the stored value is undefined. Use weakMap.has(key) to distinguish a stored undefined (true) from a missing entry (false). Unlike get(), set() throws a TypeError for an invalid key. get() itself throws a TypeError if its this is not a WeakMap instance, such as when you save the method in a variable and call it without binding it to the map.

A WeakMap does not keep a key alive just by storing it. You cannot enumerate its keys or predict when the garbage collector will reclaim an unreachable key.

Examples

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

  weakMap.set(key, 42);
  weakMap.set(pending, undefined);

  console.log(weakMap.get(key));
  console.log(weakMap.get(lookalike));
  console.log(weakMap.get(pending));
  console.log(weakMap.has(pending));
  console.log(weakMap.has(lookalike));
  console.log(weakMap.get("id"));
}

Result

42
undefined
undefined
true
false
undefined

`lookalike` has the same properties as `key` but is a different object. Both `lookalike` and `pending` give `undefined` with `get()`, but only `pending` gives `true` with `has()`. Looking up the string `"id"` returns `undefined` without throwing.

Related lessons

  • JavaScript · Lesson 35 · Basic · Version: 4
  • JavaScript · Lesson 37 · Basic · Version: 4
  • JavaScript · Lesson 4 · Intermediate · Version: 3
  • JavaScript · Lesson 10 · Intermediate · Version: 3

Sources