# .getOrInsert()

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

## How do I get a Map value or set a default if missing?

The method that returns the value associated with the key, or sets the provided default value and returns it if the key does not exist yet. Replaces the common pattern of checking `has()` before calling `set()`.

- 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 groups = new Map();
for (const item of items) {
  if (!groups.has(item.type)) groups.set(item.type, []);
  groups.get(item.type).push(item);
}
```

Right:

```js
const groups = new Map();
for (const item of items) {
  groups.getOrInsert(item.type, []).push(item);
}
```

`getOrInsert()` reads or inserts the default in one call, so the key is no longer looked up three times.

## Common mistakes

- Expecting the default to replace an existing value: it is used only when the key is missing.

## Key points

- Grouping code calls `map.getOrInsert(key, []).push(item)` instead of `has()`, `set()` and `get()`.
- Defaults that are expensive to build use `getOrInsertComputed()` instead.
- Code for older browsers has a fallback or polyfill for this method.

## Interview questions

### Does `getOrInsert()` overwrite an existing value?

No. If the key exists, it returns the stored value and ignores the default.

### What is the difference between `getOrInsert()` and `getOrInsertComputed()`?

`getOrInsert()` takes a ready default that is created on every call. `getOrInsertComputed()` takes a callback that runs only when the key is missing.

### Does WeakMap have `getOrInsert()` too?

Yes. `WeakMap` gets both `getOrInsert()` and `getOrInsertComputed()`, with the usual rule that keys must be objects.

## Related cards

- [.getOrInsertComputed()](https://wonderium.dev/js/map-get-or-insert-computed.md)
- [Map](https://wonderium.dev/js/map.md)
- [.get()](https://wonderium.dev/js/map-get.md)
- [.set()](https://wonderium.dev/js/map-set.md)

---

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