Favorites

JavaScript WeakMap Object

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
WeakMap
JavaScript Keyed Collections · ConstructorThis object is supported by all modern browsers.
Updated 28th November 2026

A WeakMap stores values against object keys without stopping those objects from being garbage-collected. It is used to attach private data to objects you don't own.

Description

A WeakMap is like a Map whose keys must be objects (or non-registered symbols) and are held weakly. If nothing else refers to a key object, it can be garbage-collected and its entry disappears. This makes WeakMaps ideal for caching results per object, or storing extra data about DOM elements, without causing memory leaks.

Because entries can vanish at any time, a WeakMap is not iterable and has no size: it only has get(), set(), has() and delete().

A typical use is storing private data for objects created by a library, keyed by the object itself, so the data goes away automatically when the object does. Another is caching the results of an expensive calculation per object. The keys must be objects or non-registered symbols; trying to use a string or number as a key throws a TypeError. When you need to list or count entries, use a regular Map instead.

Creating

new WeakMap()
new WeakMap([[key, value], ...])

Example

const visits = new WeakMap();
let user = { name: 'Sam' };

visits.set(user, 1);
visits.set(user, visits.get(user) + 1);
console.log(visits.get(user));
console.log(visits.has({ name: 'Sam' }));   // different object

user = null;   // the entry can now be garbage-collected

Browser Support

The following information will show you the current browser support for the WeakMap object. Hover over a browser icon to see the version that first introduced support for this object.

This object is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee