Skip to content

WeakMap

The WeakMap global object holds key-value pairs whose keys are objects or non-registered symbols, and it doesn’t keep those keys alive. Once nothing else in the program references a key, the garbage collector can reclaim it, and its entry disappears from the map along with it. This makes a WeakMap a way to attach extra data to an object without changing the object or extending its lifetime:

Language: JavaScript
> const draft = { title: "Release notes" };
undefined
> const lastEdited = new WeakMap([[draft, "2026-11-10"]]);
undefined

> lastEdited.get(draft)
'2026-11-10'
> lastEdited.has({ title: "Release notes" })
false

Keys match by identity, so an object with the same contents is a different key. Values can be anything, and a value stays reachable through the map only as long as its key does. The diagram traces which references keep the draft object alive:

The draft variable holds the object strongly and lastEdited holds it weakly. Once no strong references remain, the entry disappears.
Weak Keys Let Entries Vanish With Their Objects

Because entries can vanish whenever the garbage collector runs, a WeakMap has no .size and no way to list its keys, values, or entries. It isn’t iterable. The only way to read an entry is to present its key.

Syntax

The WeakMap constructor takes an optional iterable of key-value pairs:

Language: JavaScript Syntax
new WeakMap([<iterable>])
Parameter Description
iterable An optional iterable, such as an array, whose elements are two-element [key, value] arrays. Each key must be an object or a non-registered symbol

The constructor returns a new WeakMap. The new keyword is required, and calling WeakMap() without it throws a TypeError.

Key Instance Methods and Properties

Member Kind Description
.get() Instance method Returns the value for a key, or undefined when the key is missing
.has() Instance method Returns whether the map has an entry for a key
.set() Instance method Adds or updates an entry and returns the map, so calls can be chained
.getOrInsert() Instance method Returns the value for a key, first inserting a default value when the key is missing (ES2026)
.getOrInsertComputed() Instance method Returns the value for a key, first inserting the result of a callback when the key is missing (ES2026)
.delete() Instance method Removes an entry and returns whether it existed

Symbols became valid keys in ES2023, as long as they aren’t registered with Symbol.for(). That support is Baseline Newly available since 2025. .getOrInsert() and .getOrInsertComputed() were added in ES2026 and are Baseline Newly available since 2026. The rest of WeakMap is Baseline Widely available.

Examples

A report page computes an expensive total for each order object it renders. .getOrInsertComputed() caches the total per order, and the cache entry goes away when the order object does:

Language: JavaScript
> const totals = new WeakMap();
undefined
> function getTotal(order) {
…   return totals.getOrInsertComputed(order, (key) => {
…     console.log(`Computing total for order ${key.id}`);
…     return key.items.reduce((sum, item) => sum + item.price, 0);
…   });
… }
undefined
> const order = { id: 7, items: [{ price: 20 }, { price: 15 }] };
undefined

> getTotal(order)
Computing total for order 7
35
> getTotal(order)
35

The callback runs once per order, and later calls with the same order skip it.

A bank account class keeps each balance outside the instance, so the balance doesn’t show up as a property. The map is keyed by this:

Language: JavaScript
> const balances = new WeakMap();
undefined
> class Account {
…   constructor(owner, balance) {
…     this.owner = owner;
…     balances.set(this, balance);
…   }
…   deposit(amount) {
…     balances.set(this, balances.get(this) + amount);
…     return balances.get(this);
…   }
… }
undefined

> const account = new Account("Ada", 100);
undefined
> account.deposit(50)
150
> Object.keys(account)
[ 'owner' ]

When an Account instance is no longer referenced, its balance entry can be collected with it.

Common Gotchas

Primitive keys, such as strings and numbers, can’t be held weakly. Writing one throws a TypeError, but reading with one returns undefined instead of throwing:

Language: JavaScript
> const visits = new WeakMap();
undefined

> visits.set("home", 1)
Uncaught TypeError: Invalid value used as weak map key
    at WeakMap.set (<anonymous>)
> visits.get("home")
undefined

A WeakMap can’t be spread, looped over, or measured, so code that needs to list or count its entries needs a Map instead:

Language: JavaScript
> const owners = new WeakMap([[{ id: 1 }, "Ada"]]);
undefined

> owners.size
undefined
> [...owners]
Uncaught TypeError: owners is not iterable
A developer organizes records in a machine with OBJECT, MAP, KEYS and VALUES trays.

Course

JavaScript Map and Set for Pythonistas

Port a community garden's season report to JavaScript, and learn when to use a Map, a Set, or a plain object, and how to count, group, and compare without Counter or defaultdict.

intermediate js py

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Nov. 19, 2026