JS: Map.prototype.getOrInsertComputed

By Xah Lee. Date: . Last updated: .

(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"]]);

// key exist
console.assert(xx.getOrInsertComputed(5, (_) => 3) === "n5");

// key not exist
console.assert(xx.getOrInsertComputed(6, (_) => 3) === 3);

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

JavaScript. Methods for map object