JavaScript Map getOrInsert() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Map

Definition

map.getOrInsert(key, defaultValue) returns the value stored for key. If the key is missing, it first stores defaultValue and returns it. It replaces if (!map.has(k)) map.set(k, v); return map.get(k);. It is newer, added to Map and WeakMap together, and not in every engine yet: check before use.

Remember
map.getOrInsert(key, defaultValue)

key is stored     → returns the stored value (default ignored)
key is missing    → stores defaultValue, then returns it

Syntax

Call getOrInsert with a key and a default for when the key is missing.

JavaScript
map.getOrInsert(key, defaultValue)
CallWhat it does
map.getOrInsert(key, defaultValue)Return the value for key, or store defaultValue first if the key is missing.
typeof Map.prototype.getOrInsert === "function"Feature check. Run it before relying on the method.

Newer method, not in every engine yet: Node.js 24.15 lacks it in our test, Chrome 148 has it. Each example starts with a short fallback. For a costly default, use getOrInsertComputed().

Library declarations
JavaScript
map.getOrInsert(key, defaultValue)   // returns the stored or the new value

// key: any value (SameValueZero)
// defaultValue: used only if key is missing

Parameters

ParameterDescription
keyRequired. Any value. Matched with SameValueZero, so NaN finds a NaN key.
defaultValueRequired. Stored only when key is missing. Ignored when the key already has a value.

Return Value

Return ValueDescription
any valueThe value already stored for the key, or defaultValue after it has been stored.

JavaScript Examples

Example 1 — Read the Value, or Store a Default

The first call stores the default. Later calls return the stored value and ignore the new default.

JavaScript
// Fills in getOrInsert only on engines that lack it.
if (!Map.prototype.getOrInsert) {
  Object.defineProperty(Map.prototype, "getOrInsert", {
    configurable: true, writable: true,
    value(k, d) { if (!this.has(k)) this.set(k, d); return this.get(k); }
  });
}

const roles = new Map();

console.log(roles.has("ann"));                   // false
console.log(roles.getOrInsert("ann", "guest"));  // guest
console.log(roles.has("ann"));                   // true
console.log(roles.getOrInsert("ann", "admin"));  // guest
Try It Yourself

How It Works

  1. Missing key, stored default. has("ann") starts false, so "guest" is stored and returned.
  2. The entry is now real. has("ann") is now true: the default was written, not only returned.
  3. An existing value wins. "admin" is offered, but the key holds "guest", so that comes back. Nothing is replaced.

Example 2 — A Click Counter for Each Button Id

Each button id gets its own counter on the first click, with no separate has() and set().

JavaScript
// Fills in getOrInsert only on engines that lack it.
if (!Map.prototype.getOrInsert) {
  Object.defineProperty(Map.prototype, "getOrInsert", {
    configurable: true, writable: true,
    value(k, d) { if (!this.has(k)) this.set(k, d); return this.get(k); }
  });
}

const clicks = new Map();

function click(id) {
  const entry = clicks.getOrInsert(id, { count: 0 });
  entry.count += 1;
  return id + ": " + entry.count;
}

console.log(click("save"));     // save: 1
console.log(click("save"));     // save: 2
console.log(click("cancel"));   // cancel: 1
Try It Yourself

How It Works

  1. One line does three jobs. getOrInsert(id, { count: 0 }) stores a fresh counter if needed, and returns it.
  2. The same object comes back. The stored object comes back next time, so entry.count += 1 updates it.
  3. Each key has a counter. "cancel" is another key, so it starts at 0 and leaves the "save" counter alone.

Example 3 — The Default Is Built Every Time

A helper counts how often the default is built, even when the key is already there.

JavaScript
// Fills in getOrInsert only on engines that lack it.
if (!Map.prototype.getOrInsert) {
  Object.defineProperty(Map.prototype, "getOrInsert", {
    configurable: true, writable: true,
    value(k, d) { if (!this.has(k)) this.set(k, d); return this.get(k); }
  });
}

let created = 0;
function makeList() {
  created += 1;
  return [];
}

const groups = new Map();

groups.getOrInsert("team", makeList()).push("Ann");
groups.getOrInsert("team", makeList()).push("Bob");
console.log(JSON.stringify(groups.get("team")));   // ["Ann","Bob"]
console.log(created);                              // 2
Try It Yourself

How It Works

  1. Both pushes land in one list. The first call stores the list. The second returns the same list, so both names land in it.
  2. The default is made every time. makeList() runs before each call, so created is 2 although the second list is thrown away.
  3. Prefer a lazy callback for costly work. When building the default is expensive, use getOrInsertComputed() so the function runs only when needed.

Browser & Runtime Support

getOrInsert() is a newer “upsert” method. Not every engine has it yet.

✓ Newer · check support

Map.prototype.getOrInsert()

Chrome 148 (tested) has it; Node.js 24.15 does not. Check your target browsers.

Newer Not in every engine yet
Google Chrome Chrome 148 has it (tested)
Newer
Mozilla Firefox Newer versions only
Check support
Apple Safari Newer versions only
Check support
Microsoft Edge Newer versions only
Check support
Node.js Not in Node 24.15 (tested)
Not available
Deno Newer versions only
Check support
Map.prototype.getOrInsert() Check support

Bottom line: Detect it with typeof Map.prototype.getOrInsert === "function", or use the fallback shown in each example.

Frequently Asked Questions

It returns the value stored for a key. If the key is missing, it stores your default and returns it, replacing a has(), set(), get() sequence.
No. It is newer. Node.js 24.15 lacks it in our test; Chrome 148 has it. Check typeof Map.prototype.getOrInsert first.
set() always writes and replaces the old value. getOrInsert() writes only when the key is missing, and returns the value.
When the default is costly. getOrInsert() builds it before every call. getOrInsertComputed() runs a function only when the key is missing.
Use if (!map.has(key)) { map.set(key, defaultValue); } and then map.get(key).

Next: getOrInsertComputed()

Build the default only when the key is missing.

getOrInsertComputed() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful