weakMap.getOrInsertComputed(key, callbackFn) returns the value stored for key. If the key is missing, it calls callbackFn(key), stores the result, and returns it. The callback runs only when needed, so the default is built lazily. It is newer, added to Map and WeakMap together, and not in every engine yet: check before use.
Remember
weakMap.getOrInsertComputed(key, callbackFn)
key is stored → returns the stored value, callback NOT called
key is missing → callbackFn(key) runs, result is stored and returned
callback throws → nothing is stored, the error goes up
bad key → TypeError
Syntax
Call getOrInsertComputed with a key and a function that builds the default.
JavaScript
weakMap.getOrInsertComputed(key, callbackFn)
Call
What it does
weakMap.getOrInsertComputed(key, callbackFn)
Return the value for key, or call callbackFn(key) and store the result 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 cheap default, getOrInsert() is simpler.
Library declarations
JavaScript
weakMap.getOrInsertComputed(key, callbackFn) // returns the stored or the new value
// key: object or local symbol, else TypeError
// callbackFn(key): called only if key is missing
Parameters
Parameter
Description
key
Required. An object or a local symbol. Any other value throws a TypeError.
callbackFn
Required. A function called with the key, only when the key is missing. Its result is stored and returned. A non-function throws a TypeError when needed.
Return Value
Return Value
Description
any value
The value already stored for the key, or the result of callbackFn(key) after it has been stored.
JavaScript Examples
Example 1 — The Callback Runs Only When Needed
Call the method twice for the same key. Only the first call builds a value.
JavaScript
// Fills in getOrInsertComputed only on engines that lack it.
if (!WeakMap.prototype.getOrInsertComputed) {
Object.defineProperty(WeakMap.prototype, "getOrInsertComputed", {
configurable: true, writable: true,
value(k, f) { if (!this.has(k)) this.set(k, f(k)); return this.get(k); }
});
}
let calls = 0;
const data = new WeakMap();
const node = {};
const first = data.getOrInsertComputed(node, function () {
calls += 1;
return { ready: true };
});
const second = data.getOrInsertComputed(node, function () {
calls += 1;
return { ready: false };
});
console.log(first === second); // true
console.log(calls); // 1
console.log(first.ready); // true