JS: Map.prototype.getOrInsertComputed

By Xah Lee. Date: .

(new in ECMAScript 2026)

mapObj.getOrInsertComputed(key,f)

get the value of the key, if not exist, insert the key with a value from a function call, and return the value.

const xx = new Map([[4, "n4"], [5, "n5"]]);

// get the value of a existing key
console.assert(xx.getOrInsertComputed(5, (_) => 3) === "n5");

// if not exist, insert with value by a function
console.assert(xx.getOrInsertComputed(6, (_) => 3) === 3);

console.assert(xx.get(6) === 3);

JS Map.prototype