JavaScript WeakMap getOrInsert() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
WeakMap

Definition

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

Remember
weakMap.getOrInsert(key, defaultValue)

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

Syntax

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

JavaScript
weakMap.getOrInsert(key, defaultValue)
CallWhat it does
weakMap.getOrInsert(key, defaultValue)Return the value for key, or store defaultValue first if the key is missing.
typeof WeakMap.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
weakMap.getOrInsert(key, defaultValue)   // returns the stored or the new value

// key: object or local symbol, else TypeError
// defaultValue: used only if key is missing

Parameters

ParameterDescription
keyRequired. An object or a local symbol. Any other value throws a TypeError.
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 (!WeakMap.prototype.getOrInsert) {
  Object.defineProperty(WeakMap.prototype, "getOrInsert", {
    configurable: true, writable: true,
    value(k, d) { if (!this.has(k)) this.set(k, d); return this.get(k); }
  });
}

const labels = new WeakMap();
const user = { id: 1 };

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

How It Works

  1. Missing key, stored default. has(user) starts false, so "guest" is stored and returned.
  2. The entry is now real. has(user) 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

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

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

const clicks = new WeakMap();
const save = { id: "save" };
const cancel = { id: "cancel" };

function click(button) {
  const entry = clicks.getOrInsert(button, { count: 0 });
  entry.count += 1;
  return button.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(button, { 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 object, 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. The example ends with a bad key.

JavaScript
// Fills in getOrInsert only on engines that lack it.
if (!WeakMap.prototype.getOrInsert) {
  Object.defineProperty(WeakMap.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 WeakMap();
const team = {};

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 {
  groups.getOrInsert("team", []);
} catch (e) {
  console.log(e.name);                           // TypeError
}
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. A string cannot be a key. "team" is not an object, so getOrInsert() throws a TypeError.

Browser & Runtime Support

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

✓ Newer · check support

WeakMap.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
WeakMap.prototype.getOrInsert() Check support

Bottom line: Detect it with typeof WeakMap.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 WeakMap.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 (!wm.has(key)) { wm.set(key, defaultValue); } and then wm.get(key).

Next: getOrInsertComputed()

Build the default only when the key is missing.

getOrInsertComputed() tutorial →

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