# .getOrInsertComputed()

> The `.getOrInsertComputed()` JS method of the `Map` object returns the value for a key, inserting a computed value if the key is missing.

## How do I get or set a Map value with a computed default?

The method that returns the value associated with the key, or calls a callback to compute a default value, stores it and returns it. The callback is executed only when the key is missing, which avoids unnecessary computations.

- Topic: Map
- Type: method
- Browser support: Chrome 145+, Chrome Android 145+, Edge 145+, Firefox 144+, Firefox Android 144+, Safari 26.2+, Safari iOS 26.2+

## Example

Wrong:

```js
const cache = new Map();
function getUser(id) {
  return cache.getOrInsert(id, loadUser(id));
}
```

Right:

```js
const cache = new Map();
function getUser(id) {
  return cache.getOrInsertComputed(id, (key) => loadUser(key));
}
```

The callback runs only for missing keys, so `loadUser()` is no longer called on every cache hit.

## Common mistakes

- Using `getOrInsert()` with an expensive default, which is created on every call.

## Key points

- Expensive defaults are created in the callback of `getOrInsertComputed()`, so they are built only for missing keys.
- The code does not use the `has()`, `set()`, `get()` sequence for the same key.
- Code for older browsers has a fallback or polyfill for this method.

## Interview questions

### What arguments does the `getOrInsertComputed()` callback receive?

It receives the key as its only argument, so `map.getOrInsertComputed(id, loadUser)` passes `id` to `loadUser`.

### Can the `getOrInsertComputed()` callback be async?

Yes, but the Map then stores the returned promise, not the resolved value. That is a valid way to share one in-flight request per key.

## Related cards

- [.getOrInsert()](https://wonderium.dev/js/map-get-or-insert.md)
- [Map](https://wonderium.dev/js/map.md)
- [WeakMap](https://wonderium.dev/js/weak-map.md)
- [Map.groupBy()](https://wonderium.dev/js/map-group-by.md)

---

- Level: [JavaScript](https://wonderium.dev/js.md)
- HTML version: https://wonderium.dev/js/map-get-or-insert-computed
- Last updated: 2026-11-25
