Newly availableHelpful for caches, grouping logic, and memoization where default creation is a repeated pattern.

Overview

Map.getOrInsert() combines lookup and initialization into a single operation. It simplifies the common pattern of checking for a key, creating a default value, and then returning the stored result.

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
1+Supported (version) Not supported Has note Sub-feature descriptions sourced from MDN Web Docs (CC BY-SA 2.5)

Syntax

JAVASCRIPT
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.

JavaScript
Output
Press the Run button

Build grouped buckets

Create arrays on demand when grouping records into a Map.

JavaScript
Output
Press the Run button

Reuse existing entries

Confirm that the same key does not recreate the stored value.

JavaScript
Output
Press the Run button

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.

Powered by web-features