MENU
Upsert--getOrInsert()
A very common Map pattern is 'get the value for this key, or compute and store a default if it is not there yet' — previously requiring an awkward .has()-then-.get()-or-.set() dance (and two lookups instead of one). ECMAScript 2026 adds an 'upsert' (update-or-insert) pair of methods, shared by Map and WeakMap, that do this atomically in a single operation.
Map.prototype.getOrInsert(key, value) returns the existing value for key if present; otherwise it inserts value under key and returns that value.
Map.prototype.getOrInsertComputed(key, callbackFn) is the same, except the default is computed lazily by calling callbackFn(key) — and only when key is actually missing — instead of always being evaluated up front like the plain value passed to getOrInsert().
const cache = new Map();
function getGroup(name) {
return cache.getOrInsertComputed(name, () => {
console.log('creating group:', name); // only logged the first time per name
return [];
});
}
getGroup('admins').push('alice');
getGroup('admins').push('bob');
console.log(cache.get('admins'));
const counts = new Map();
counts.getOrInsert('x', 0);
counts.set('x', counts.get('x') + 1);
console.log(counts.get('x'));WeakMap.prototype.getOrInsert() and WeakMap.prototype.getOrInsertComputed() (15) work identically, for the same key-must-already-exist-or-get-created situation with object keys.