JavaScript WeakMap

Beginner
8 min read
Updated: Nov 2026
3 examples
Weak keys

Definition and Usage

In JavaScript, a WeakMap stores pairs of a key and a value. The key must be an object. The value can be anything. You create one with new WeakMap(), then use set(), get(), has(), and delete().

The word weak is about memory. A WeakMap does not keep its keys alive. If nothing else in your program uses a key object, JavaScript may throw that object away, and its entry leaves the WeakMap with it. You never see this happen.

That is why a WeakMap has no size, no clear(), and cannot be looped over. A list of entries would change whenever memory is cleaned up. This page teaches the ideas; the WeakMap Methods index lists every method guide (set(), get(), and more).

Key = object, value = anything.

A WeakMap lets you attach extra data to an object without changing the object and without stopping it from being cleaned up.

JavaScript Syntax

Common ways to create a WeakMap and use it:

JavaScript
const wm = new WeakMap();                 // empty
const key = { id: 1 };                     // keys must be objects

wm.set(key, "data");                       // store (returns wm)
wm.get(key);                               // "data"
wm.has(key);                               // true
wm.delete(key);                            // true

const filled = new WeakMap([[key, "again"]]);   // start with pairs

What Weak Means

A normal Map holds its keys strongly. After map.set(user, data), the user object stays in memory for as long as the Map lives, even if the rest of your program forgot it. Over time that is a memory leak.

A WeakMap holds its keys weakly. When the key is no longer used anywhere else, the engine may clean up the key. Its value is cleaned up too, unless something else points to it. The value is only kept while the key is alive.

You cannot watch this in a small script, because the engine decides when to clean up. So no example on these pages depends on it. Related tools are FinalizationRegistry, WeakRef, and WeakSet.

Which Keys Are Allowed

Keys can be objects, including arrays and functions. Since ES2023 they can also be symbols made with Symbol("name"). Strings, numbers, booleans, null, undefined, and registered symbols from Symbol.for() are not allowed.

set() throws a TypeError for a bad key. get(), has(), and delete() never throw: they return undefined, false, and false. A different object with the same shape is a different key, because objects are matched by identity.

When to Use a WeakMap

UseHow it worksWhy WeakMap fits
Private dataStore hidden fields in a WeakMap keyed by thisThe data goes away with the object
Cache by objectRemember an expensive result for each objectThe cache never keeps old objects alive
DOM node notesAttach extra info to elements you do not ownA removed element frees its notes
MemoizationSkip repeated work when called again with the same objectNo cleanup code to write

Map vs WeakMap

QuestionMapWeakMap
Allowed keysAny valueObjects (and local symbols) only
Keeps keys alive?Yes, until you delete themNo, keys can be cleaned up
Sizemap.sizeNone
Loop over entriesfor...of, forEach(), keys()Not possible
Empty itclear()Create a new WeakMap
Best forData you want to list, count, or showHidden extra data about objects

Newer Upsert Methods

getOrInsert() and getOrInsertComputed() read a value, and store one first if the key is missing. They were added to Map and WeakMap together and replace the long if (!wm.has(k)) wm.set(k, v) pattern.

They are not in every engine yet. We tested Node.js 24.15, which does not have them, and Chrome 148, which does. Check before you rely on them: typeof WeakMap.prototype.getOrInsert === "function". Their examples include a tiny fallback so they still run everywhere.

JavaScript Examples

Three short programs that show how a WeakMap works.

Example 1 — Store, Read, Check, and Remove

Use an object as the key and walk through the four classic methods in order.

JavaScript
const wm = new WeakMap();
const key = { name: "settings" };

wm.set(key, 42);
console.log(wm.get(key));    // 42
console.log(wm.has(key));    // true
console.log(wm.delete(key)); // true
console.log(wm.has(key));    // false
set() tutorial

How It Works

  1. Object in, value out. wm.set(key, 42) ties the number 42 to the key object, and get(key) reads it back.
  2. Ask before you read. has(key) answers true or false without returning the value.
  3. Remove on purpose. delete(key) returns true because there was an entry, and the last has() confirms it is gone.

Example 2 — What a WeakMap Does Not Have

A Map can tell you its size and loop over its entries. A WeakMap cannot, on purpose.

JavaScript
const map = new Map([["a", 1]]);
const wm = new WeakMap();

console.log(map.size);                // 1
console.log(typeof map.forEach);      // function
console.log(typeof wm.size);          // undefined
console.log(typeof wm.forEach);       // undefined
console.log(typeof wm.clear);         // undefined
has() tutorial

How It Works

  1. A Map is a visible list. map.size is 1 and forEach is a function, so you can count and loop over its entries.
  2. A WeakMap hides its contents. size, forEach, and clear all have type "undefined" because the WeakMap does not offer them.
  3. The reason is memory. Entries may disappear whenever their key is cleaned up, so any list or count would be out of date. The only questions you can ask are about keys you hold.

Example 3 — Fill a WeakMap with Pairs

Pass a list of [key, value] pairs to the constructor. Every key in the list must be an object.

JavaScript
const a = { id: "a" };
const b = { id: "b" };
const meta = new WeakMap([[a, "first"], [b, "second"]]);

console.log(meta.get(b));                          // second
console.log(meta.get({ id: "a" }) === undefined);  // true

try {
  new WeakMap([["a", 1]]);
} catch (e) {
  console.log(e.name);                             // TypeError
}
get() tutorial

How It Works

  1. Two pairs at once. The constructor calls set() for each pair, so a and b are stored before any other code runs.
  2. Look-alikes are not keys. A new { id: "a" } has the same fields as a but is a different object, so get() finds nothing.
  3. The same key rule applies. A string key in the list breaks the rule, so the constructor throws a TypeError.

WeakMap Method Groups

WeakMap has only six methods. Each one has a full tutorial with examples you can run in the browser.

MethodUse it to
set()Store a value for an object key (chainable)
get()Read the value, or undefined if the key is missing
has()Ask whether a key is in the WeakMap
delete()Remove one entry on purpose
getOrInsert()Read the value, or store a default first (newer)
getOrInsertComputed()Same, but build the default only when needed (newer)

Full list with the constructor: WeakMap Methods index.

Frequently Asked Questions

A WeakMap is a collection of key and value pairs where every key must be an object. The keys are held weakly: the WeakMap does not stop the engine from cleaning up a key that nothing else uses. You create one with new WeakMap() and use set(), get(), has(), and delete().
Strings and numbers are plain values that are never cleaned up like objects, so there would be nothing to hold weakly. set() throws a TypeError for them. Objects (including arrays and functions) work, and since ES2023 so do symbols made with Symbol().
Entries can disappear whenever the engine cleans up a key, and that timing is not predictable. A size or a list would be wrong a moment later, so WeakMap only lets you ask about keys you already hold.
A Map accepts any key, keeps keys alive, has size, and can be looped over. A WeakMap accepts only objects as keys, does not keep them alive, and cannot be counted or looped. Choose a Map for data you show or count, and a WeakMap for hidden extra data about objects.
Use it when data belongs to an object and should disappear with it: private fields, a cache keyed by object, notes about DOM elements, or memoized results. If you need to list or count the entries, use a Map instead.

Browse every WeakMap method

Open the index for delete(), get(), getOrInsert(), getOrInsertComputed(), has(), and set().

WeakMap Methods index →

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.

16 people found this page helpful