"Get the value, or store a default first" used to need has(), set() and get(). The Upsert proposal reached Stage 4 for ES2026 (Baseline 2026). getOrInsert(key, value) returns the existing value or inserts value; getOrInsertComputed(key, callback) calls callback(key) only for a missing key. Map and WeakMap have both. Node.js 25.8 2,131 lacks them, so this output comes from headless Chrome 152 1 .
const words = ['apple', 'avocado', 'banana', 'apple'];
const groups = new Map();
const counts = new Map();
for (const w of words) {
groups.getOrInsertComputed(w[0], (letter) => {
console.log('new group', letter); // runs only for missing keys
return [];
}).push(w);
counts.set(w, counts.getOrInsert(w, 0) + 1);
}
console.log(JSON.stringify([...groups]), JSON.stringify([...counts]));new group a new group b [["a",["apple","avocado","apple"]],["b",["banana"]]] [["apple",2],["avocado",1],["banana",1]]
getOrInsert(key, []) would allocate an array on every call; pass a callback instead. core-js 25,536 polyfills both.