Map getOrInsert()
The getOrInsert() method of Map instances returns the value corresponding to the specified key in this Map. If the key is not present, it inserts a new entry with the key and a given default value, and returns the inserted value.
If the computation of the default value is expensive, consider using Map.prototype.getOrInsertComputed() instead, which takes a callback to compute the default value only if it's actually needed.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 145 | 145 | 144 | 26.2 | 145 | 26.2 | |
| Built-in object | ||||||
| The getOrInsertComputed() method of Map instances returns the value corresponding to the specified key in this Map. If the key is not present, it inserts a new entry with the key and a default value computed from a given callback, and returns the inserted value. | 145 | 145 | 144 | 26.2 | 145 | 26.2 |
| The getOrInsert() method of WeakMap instances returns the value corresponding to the specified key in this WeakMap. If the key is not present, it inserts a new entry with the key and a given default value, and returns the inserted value. | 145 | 145 | 144 | 26.2 | 145 | 26.2 |
| The getOrInsertComputed() method of WeakMap instances returns the value corresponding to the specified key in this WeakMap. If the key is not present, it inserts a new entry with the key and a default value computed from a given callback, and returns the inserted value. | 145 | 145 | 144 | 26.2 | 145 | 26.2 |
Syntax
const map = new Map();
map.getOrInsert('key', 'default');
// If 'key' is not in the map, set it to 'default' and return it Live demo
Get or insert into a Map
Use the proposal if available, otherwise fall back to a helper.
Build grouped buckets
Create arrays on demand when grouping records into a Map.
Reuse existing entries
Confirm that the same key does not recreate the stored value.
Use cases
-
Bucket creation
Initialize arrays, sets, or counters in a map only when a key appears for the first time.
-
Memoized storage
Create and retain derived values lazily without writing repetitive key-exists checks.
Cautions
- Use a clear default creation strategy so inserted values remain predictable and side effects stay obvious.
- If the initialization step is expensive or async, make the lifecycle explicit instead of hiding too much in one call.
Accessibility
- This feature affects data organization rather than UI directly.
- Cleaner state initialization can still reduce bugs in user-facing collections and lists.