weakMap.getOrInsert(key, defaultValue) returns the value stored for key. If the key is missing, it first stores defaultValue and returns it. It replaces if (!wm.has(k)) wm.set(k, v); return wm.get(k);. It is newer, added to Map and WeakMap together, and not in every engine yet: check before use. A bad key throws a TypeError.
Remember
weakMap.getOrInsert(key, defaultValue)
key is stored → returns the stored value (default ignored)
key is missing → stores defaultValue, then returns it
bad key → TypeError
Syntax
Call getOrInsert with a key and a default for when the key is missing.
JavaScript
weakMap.getOrInsert(key, defaultValue)
Call
What it does
weakMap.getOrInsert(key, defaultValue)
Return the value for key, or store defaultValue first if the key is missing.
Feature check. Run it before relying on the method.
Newer method, not in every engine yet: Node.js 24.15 lacks it in our test, Chrome 148 has it. Each example starts with a short fallback. For a costly default, use getOrInsertComputed().
Library declarations
JavaScript
weakMap.getOrInsert(key, defaultValue) // returns the stored or the new value
// key: object or local symbol, else TypeError
// defaultValue: used only if key is missing
Parameters
Parameter
Description
key
Required. An object or a local symbol. Any other value throws a TypeError.
defaultValue
Required. Stored only when key is missing. Ignored when the key already has a value.
Return Value
Return Value
Description
any value
The value already stored for the key, or defaultValue after it has been stored.
JavaScript Examples
Example 1 — Read the Value, or Store a Default
The first call stores the default. Later calls return the stored value and ignore the new default.
JavaScript
// Fills in getOrInsert only on engines that lack it.
if (!WeakMap.prototype.getOrInsert) {
Object.defineProperty(WeakMap.prototype, "getOrInsert", {
configurable: true, writable: true,
value(k, d) { if (!this.has(k)) this.set(k, d); return this.get(k); }
});
}
const labels = new WeakMap();
const user = { id: 1 };
console.log(labels.has(user)); // false
console.log(labels.getOrInsert(user, "guest")); // guest
console.log(labels.has(user)); // true
console.log(labels.getOrInsert(user, "admin")); // guest