JS: Map.prototype.getOrInsert

By Xah Lee. Date: .

(new in ECMAScript 2026)

mapObj.get(key, newVal)

get the value of the key, if not exist, insert it and return the value.

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

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

// get the value of a key if non-exist, insert it with a value
console.assert(xx.getOrInsert(6, "n6") === "n6");

console.assert(xx.getOrInsert(6) === "n6");

JS Map.prototype