CKTIS / JavaScript
WeakMap.set(): add or replace a value
Use `set()` to store a value under a key in a `WeakMap`. It replaces the value if the key already exists and 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.set refers to the instance method WeakMap.prototype.set, not a static method on the WeakMap constructor. weakMap.set(key, value) adds an entry for a new key or replaces the value for an existing key. It returns the same WeakMap, so you can chain another .set() call. The value can be anything; omitting value stores undefined.
Object keys are compared by identity: two separately created {} objects are different keys. ECMAScript 2024 also accepts non-registered symbols such as Symbol(). Older runtimes may support only object keys. A string, number, null, or registered symbol from Symbol.for() is an invalid key and causes a TypeError. Calling the method with a this value that is not a WeakMap instance also causes a TypeError.
An entry does not keep its key alive by itself. When the key is no longer reachable apart from this weak association, it can be garbage-collected, but there is no guarantee when. This is useful for storing extra data about an object without extending its lifetime. Use Map instead if you need string keys or need to iterate over entries.
Examples
{
const statuses = new WeakMap();
const task = {};
const otherTask = {};
const result = statuses.set(task, "pending").set(otherTask, false);
statuses.set(task, "ready");
console.log(result === statuses);
console.log(statuses.get(task));
console.log(statuses.get(otherTask));
console.log(statuses.has({}));
try {
statuses.set("task", "ready");
} catch (error) {
console.log(error instanceof TypeError);
}
}Result
true ready false false true
The first `true` shows that the chained calls return the same map. `ready` replaces `pending`, the first `false` is the stored value for `otherTask`, and the second `false` means the new `{}` is not a key in the map. The final `true` confirms that the string key caused a `TypeError`.
Related lessons
- JavaScript · Lesson 18 · Basic · Version: 4