JavaScript WeakMap Methods

About This Index
This page is the JavaScript WeakMap Methods index for the tutorial track. Each row links to a full guide with syntax, three runnable examples, browser notes, and FAQs.
Learn what a WeakMap is on /js/weakmap. Use this page when you need a specific API such as set(), get(), or delete().
Every WeakMap method takes an object as the key. set() throws a TypeError for a string or number. get(), has(), and delete() never throw: they answer undefined or false.
How to Call a WeakMap Method
Every method is called with a dot on the WeakMap. There are no static helpers:
const wm = new WeakMap();
const user = { name: "Ann" };
wm.set(user, "admin"); // store a value (returns wm)
wm.get(user); // "admin"
wm.has(user); // true
wm.delete(user); // true
// Newer upsert methods: check support first
wm.getOrInsert(user, "guest");
wm.getOrInsertComputed(user, function (key) { return "guest"; }); JavaScript WeakMap Methods Table
All method guides in this JavaScript tutorial series (6 tutorials), grouped by what they do.
Store and update
3 methodsAttach a value to an object key. set() always writes; the two newer upsert methods write only when the key is missing.
| Method | Description | Tutorial |
|---|---|---|
set() | Store a value for an object key. Returns the WeakMap, so calls can be chained. | Open |
getOrInsert() | Read the value for a key, or store a default first when the key is missing (newer method). | Open |
getOrInsertComputed() | Read the value for a key, or call a function to build and store it when the key is missing (newer method). | Open |
Read
2 methodsLook a key up without changing anything. Neither method ever throws, even for keys that WeakMap cannot hold.
Remove
1 methodDelete one entry on purpose. You do not need this for memory: dead keys are cleaned up for you.
WeakMap Constructor and What Is Missing
A WeakMap is small on purpose. Here is how to create one, and the things it does not have. Compare this with a Map, which has all of them.
| Member | What it gives you | Since |
|---|---|---|
new WeakMap() | Create an empty WeakMap. | ES2015 |
new WeakMap([[key, value], ...]) | Create a WeakMap that already holds some pairs. Every key must be an object or a local symbol. | ES2015 |
weakMap.size | Does not exist. A WeakMap cannot tell you how many entries it holds, so you get undefined. | Not available |
weakMap.clear() | Does not exist. To start over, create a new WeakMap. | Not available |
weakMap.keys(), values(), entries(), forEach() | None of these exist. A WeakMap cannot be listed. | Not available |
for (const x of weakMap) | Throws a TypeError. A WeakMap is not iterable. | Not available |
Symbol("id") as a key | Local symbols (made with Symbol(), not Symbol.for()) are allowed as keys. | ES2023 |
Frequently Asked Questions
Start with delete()
Learn how to remove an entry on purpose, and why you rarely have to.
14 people found this page helpful
