Master Code
On The Go

Learn. Practice. Build.

Home › Code Snippets › JavaScript › Reference › Map.getOrInsert()

ECMAScript 2026

⚠️ Baseline Newly Available

Map.prototype.getOrInsert()

Get a value, or insert and return a default if missing. Kills has/set boilerplate.

Last updated: October 2026

Definition: map.getOrInsert(key, defaultValue) returns the value for the given key. If the key does not exist, it inserts defaultValue and returns it. It also comes in a lazy variant: getOrInsertComputed(key, callbackFn) [citation:1][citation:20].

🎬 Live Example

Five common getOrInsert patterns. Click any button to see the output.

Input:

                
Output:

            

💡 getOrInsertComputed only runs the callback if the key is missing.

📝

Basic Syntax

map.getOrInsert(key, defaultValue)
map.getOrInsertComputed(key, callbackFn)

// Returns existing value, or inserts and returns default
// getOrInsertComputed is lazy — callback only runs if missing

🎯 Syntax & Parameters

Parameter Type Description
keyanyKey to look up.
defaultValueanyValue inserted if key is missing.
callbackFnFunctionOnly for getOrInsertComputed. Returns default lazily.
1

Basic getOrInsert

const m = new Map();
m.getOrInsert("a", 1);  // 1 (inserted)
m.getOrInsert("a", 99); // 1 (existing, no change)

m; // Map { 'a' => 1 }
2

getOrInsertComputed (Lazy)

const m = new Map();

m.getOrInsertComputed("a", () => {
  console.log("computing");
  return 1;
});
// Logs "computing", returns 1

m.getOrInsertComputed("a", () => {
  console.log("computing again"); // NOT logged
  return 2;
});
// Returns 1 — callback skipped

Pro tip: Use computed for expensive operations or when you need a fresh object per key.

3

Grouping Pattern

const items = [
  { type: "fruit", name: "apple" },
  { type: "veg", name: "carrot" },
  { type: "fruit", name: "banana" }
];

const grouped = new Map();
for (const item of items) {
  grouped.getOrInsertComputed(item.type, () => []).push(item);
}
// Map { 'fruit' => [...], 'veg' => [...] }

Why this works: A fresh array is created per key, avoiding the shared-array bug from getOrInsert(key, []).

4

Counter Pattern

const counts = new Map();
const words = ["hello", "world", "hello"];

for (const word of words) {
  counts.getOrInsert(word, 0);
  counts.set(word, counts.get(word) + 1);
}
// Map { 'hello' => 2, 'world' => 1 }
5

Real-World: Cache Layer

const cache = new Map();

async function getUser(id) {
  return cache.getOrInsertComputed(id, () => {
    return fetch(`/api/users/${id}`).then(r => r.json());
  });
}

// First call: fetches and caches
// Subsequent calls: returns cached promise

🎯 getOrInsert vs getOrInsertComputed

Method Evaluates Use when
getOrInsertAlwaysDefault is cheap (primitives, existing refs)
getOrInsertComputedOnly if missingDefault is expensive or needs fresh object

⚠️ Common Mistakes

❓ Frequently Asked Questions

What does Map.getOrInsert() do in JavaScript?

Map.getOrInsert(key, defaultValue) returns the value for the given key. If the key does not exist, it inserts the default value and returns it. It eliminates the common has/set/get boilerplate.

What is the difference between getOrInsert and getOrInsertComputed?

getOrInsert takes a ready-to-use value. getOrInsertComputed takes a callback that computes the value lazily, only when the key is missing. Use getOrInsertComputed for expensive computations or fresh objects per key.

Does getOrInsert work on WeakMap?

Yes. WeakMap.prototype.getOrInsert() and WeakMap.prototype.getOrInsertComputed() are also part of ECMAScript 2026.

When was getOrInsert added to JavaScript?

Map.getOrInsert() and getOrInsertComputed() were approved as part of ECMAScript 2026 (June 2026). They reached Baseline Newly Available in early 2026.

What happens if the key exists with a falsy value?

getOrInsert only checks for key existence, not value truthiness. If the key exists with a value of 0, '', or null, that value is returned as-is.

🎯 What's Next?

← All JavaScript Reference