JavaScript WeakMap set() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
WeakMap

Definition

weakMap.set(key, value) stores value under key and returns the same WeakMap. The key must be an object (or a local symbol, since ES2023). If the key is already in the WeakMap, its old value is replaced. If the key is not allowed, set() throws a TypeError. The WeakMap does not keep the key alive: when nothing else uses the key, it can be cleaned up together with its value.

Remember
weakMap.set(key, value)   → the same WeakMap

key = object         → stored
key = local symbol   → stored (ES2023)
key = string/number  → TypeError
key already there    → value is replaced

set(a, 1).set(b, 2)  → chaining works

Syntax

Call set on a WeakMap with an object key and any value.

JavaScript
weakMap.set(key, value)
CallWhat it does
weakMap.set(key, value)Store value for key. Replaces an older value for the same key.
weakMap.set(a, 1).set(b, 2)Chain calls. Each set() returns the WeakMap, so the next call can follow it.

Built into JavaScript since ES2015. Local symbols as keys need ES2023. To store a value only when the key is missing, see getOrInsert().

Library declarations
JavaScript
weakMap.set(key, value)   // returns the WeakMap

// key:   an object, or a local symbol (ES2023)
// value: anything
// throws TypeError if key cannot be held weakly

Parameters

ParameterDescription
keyRequired. An object (including arrays and functions) or a local symbol made with Symbol(). Strings, numbers, booleans, null, undefined, and Symbol.for() symbols are rejected.
valueRequired. Any value: a number, a string, an object, a function, even undefined.

Return Value

Return ValueDescription
WeakMapThe same WeakMap you called set() on, so calls can be chained.

JavaScript Examples

Example 1 — Store, Chain, and Replace

Store ages for two people, chain two calls together, and see what happens when the same key is stored twice.

JavaScript
const ages = new WeakMap();
const ann = { name: "Ann" };
const bob = { name: "Bob" };

const result = ages.set(ann, 31);
console.log(result === ages);     // true

ages.set(bob, 27).set(ann, 32);
console.log(ages.get(ann));       // 32
console.log(ages.get(bob));       // 27
Try It Yourself

How It Works

  1. set() hands back the map. ages.set(ann, 31) returns ages itself, so the comparison with ages prints true.
  2. Calls can be chained. The next line stores Bob and then stores Ann again, because each set() gives back the WeakMap for the call that follows.
  3. Same key, new value. Ann was stored as 31 and then as 32. A key holds one value, so the later call wins, and Bob stays at 27.

Example 2 — Which Keys Work

Try eight different keys. Objects are accepted. Plain values and registered symbols are rejected with a TypeError.

JavaScript
const wm = new WeakMap();
const tests = [
  ["object", {}],
  ["array", []],
  ["function", function () {}],
  ["local symbol", Symbol("id")],
  ["string", "text"],
  ["number", 42],
  ["null", null],
  ["registered symbol", Symbol.for("shared")]
];

tests.forEach(function (t) {
  try {
    wm.set(t[1], true);
    console.log(t[0] + ": ok");
  } catch (e) {
    console.log(t[0] + ": " + e.name);
  }
});
Try It Yourself

How It Works

  1. Objects of every kind work. A plain object, an array, and a function are all objects, so each one is accepted as a key.
  2. Local symbols work too. Symbol("id") is allowed since ES2023. A symbol from Symbol.for() is shared everywhere, so it is rejected.
  3. Plain values throw. Strings, numbers, and null are not objects. set() throws a TypeError, and the catch block prints the error name.

Example 3 — Hidden Data for Each Object

Keep a counter for every object outside the object itself. This is the most common job for a WeakMap.

JavaScript
const secrets = new WeakMap();

class Counter {
  constructor(start) {
    secrets.set(this, { count: start });
  }
  next() {
    const state = secrets.get(this);
    state.count += 1;
    return state.count;
  }
}

const a = new Counter(10);
const b = new Counter(100);
console.log(a.next());               // 11
console.log(a.next());               // 12
console.log(b.next());               // 101
console.log(Object.keys(a).length);  // 0
Try It Yourself

How It Works

  1. One map, many objects. The secrets WeakMap sits outside the class. Every constructor call adds one entry, with this as the key.
  2. Every object has its own state. a counts 11 and 12 while b starts from 100, because each lookup uses the object as the key.
  3. Nothing shows on the object. Object.keys(a).length is 0, so outside code cannot see the counter, and it can be cleaned up when a is.

Browser & Runtime Support

WeakMap.prototype.set() is part of ES2015 (ES6), together with Map, Set, and WeakSet.

✓ Baseline · ES2015

WeakMap.prototype.set()

Works in every modern browser, plus Node.js, Deno, and Bun. Internet Explorer 11 has a basic WeakMap with set(), get(), has(), and delete(), but not the constructor argument.

98% Modern browser support
Google Chrome 36+ · Desktop & Mobile
Full support
Mozilla Firefox 6+ · Desktop & Mobile
Full support
Apple Safari 8+ · macOS & iOS
Full support
Microsoft Edge 12+
Full support
Node.js 0.12+ · every current release
Supported
Deno All releases
Supported
Internet Explorer IE 11 · no constructor argument
Basic
WeakMap.prototype.set() Excellent

Bottom line: Safe to use in any modern browser and runtime. Only the local symbol as a key feature is newer (ES2023), so keep to object keys if you must support older browsers.

Frequently Asked Questions

It stores a value under a key in a WeakMap and returns the WeakMap. The key must be an object (or a local symbol). If the key already exists, its value is replaced.
Because the key is not allowed. A WeakMap can only hold objects and local symbols weakly. Strings, numbers, booleans, null, undefined, and symbols from Symbol.for() cannot be used as keys, so set() throws and stores nothing.
Yes. A key has only one value. Calling set() again with the same key overwrites the old value. If you want to keep the old value, use getOrInsert() instead.
Yes. set() returns the WeakMap, so wm.set(a, 1).set(b, 2) works. This is also a handy way to fill a WeakMap in one statement.
No. The WeakMap holds the key weakly and the value only while the key is alive. Once nothing else uses the key, the pair can be cleaned up, even if the value points back to the key.

Back to the WeakMap Method Index

See all six methods in one place, plus the things a WeakMap does not have.

WeakMap methods →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful