Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

WeakMap.prototype.set(): store a value for a key

Use `set()` to insert an entry into a `WeakMap` or replace the value for an existing key. It returns the same map so you can chain calls.

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

Syntax

weakMap.set(key, value)

WeakMap.prototype.set is a prototype method you call on an instance: weakMap.set(key, value). It adds an entry for a new key or replaces the value for the same key. It returns the same instance, not the stored value, so you can chain another .set() call. The value can be any JavaScript value, including undefined.

Object keys are compared by identity: two separate objects with identical properties are different keys. ECMAScript 2024 also permits non-registered symbols such as Symbol("id"). Symbols from Symbol.for("id") and other primitives such as strings are not valid keys. Older runtimes may not support symbol keys; check your target runtime.

An invalid key throws a TypeError. Calling a detached method without the right this also throws a TypeError: the receiver must be a WeakMap instance.

The entry does not itself keep the key alive. If the key is no longer otherwise reachable, it can be garbage-collected; do not rely on when that happens. You cannot enumerate WeakMap keys. If you need to iterate over keys or use strings as keys, use a Map instead.

Examples

{
  const metadata = new WeakMap();
  const item = { id: 1 };

  metadata.set(item, 10);
  console.log(metadata.get(item));

  const returned = metadata.set(item, 20);
  console.log(returned === metadata);
  console.log(metadata.get(item));
  console.log(metadata.has({ id: 1 }));

  try {
    metadata.set("id", 30);
  } catch (error) {
    console.log(error instanceof TypeError);
  }
}

Result

10
true
20
false
true

The first lookup returns `10`; after the update it returns `20`. The comparison `returned === metadata` is `true`. A fresh object with the same `id` is not the stored key, so `has()` returns `false`. The attempt to use a string key throws a `TypeError`, which is caught.

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