JavaScript WeakMap getOrInsertComputed() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
WeakMap

Definition

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)
CallWhat it does
weakMap.getOrInsertComputed(key, callbackFn)Return the value for key, or call callbackFn(key) and store the result if the key is missing.
typeof WeakMap.prototype.getOrInsertComputed === "function"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

ParameterDescription
keyRequired. An object or a local symbol. Any other value throws a TypeError.
callbackFnRequired. 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 ValueDescription
any valueThe 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
Try It Yourself

How It Works

  1. The first call builds the value. The key is missing, so the first function runs and its object is stored.
  2. The second call skips its function. The key has a value now, so the second function never runs: calls stays 1.
  3. Both calls share one object. first === second is true, so ready is still true.

Example 2 — Compute a Value from the Key

The callback receives the key, so a ready-made function works.

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); }
  });
}

const sizes = new WeakMap();
const box = { w: 3, h: 4 };

function area(shape) {
  return shape.w * shape.h;
}

console.log(sizes.getOrInsertComputed(box, area));   // 12
box.w = 10;
console.log(sizes.getOrInsertComputed(box, area));   // 12
console.log(area(box));                              // 40
Try It Yourself

How It Works

  1. The key is passed in. The first call runs area(box) for you, so a plain function works as the callback.
  2. The answer is remembered. After box.w = 10, the second call still returns 12: the stored value is reused.
  3. Stored values can go stale. area(box) now gives 40. Cache only results that will not change.

Example 3 — A Failing Callback Stores Nothing

If the function throws, the key stays missing and a retry works.

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); }
  });
}

const cache = new WeakMap();
const task = {};

try {
  cache.getOrInsertComputed(task, function () {
    throw new Error("fail");
  });
} catch (e) {
  console.log(e.message);       // fail
}
console.log(cache.has(task));   // false

console.log(cache.getOrInsertComputed(task, function () { return "ok"; }));   // ok
console.log(cache.has(task));   // true
Try It Yourself

How It Works

  1. The error comes out. The callback throws, so the method throws, and catch prints fail.
  2. No half-saved entry. Nothing was stored, so has(task) is false.
  3. A retry works. The next call finds the key missing, runs a working function, and stores "ok".

Browser & Runtime Support

getOrInsertComputed() is a newer “upsert” method. Not every engine has it yet.

✓ Newer · check support

WeakMap.prototype.getOrInsertComputed()

Chrome 148 (tested) has it; Node.js 24.15 does not. Check your target browsers.

Newer Not in every engine yet
Google Chrome Chrome 148 has it (tested)
Newer
Mozilla Firefox Newer versions only
Check support
Apple Safari Newer versions only
Check support
Microsoft Edge Newer versions only
Check support
Node.js Not in Node 24.15 (tested)
Not available
Deno Newer versions only
Check support
WeakMap.prototype.getOrInsertComputed() Check support

Bottom line: Detect it with typeof WeakMap.prototype.getOrInsertComputed === "function", or use the fallback shown in each example.

Frequently Asked Questions

It returns the value stored for a key. If the key is missing, it calls your function with the key, stores the result, and returns it.
getOrInsert() takes a ready-made default, built before every call. getOrInsertComputed() takes a function, called only if the key is missing.
No. It is newer. Node.js 24.15 lacks it in our test; Chrome 148 has it. Check typeof WeakMap.prototype.getOrInsertComputed first.
The key itself, so you can pass an existing function such as area(shape) with no wrapper.
The error passes out and nothing is stored, so a later call can run the callback again.

Next: has()

Check a key without reading or changing it.

has() tutorial →

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.

11 people found this page helpful