Map.prototype.getOrInsert()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
ThegetOrInsert() method ofMap instances returns the value corresponding to the specified key in thisMap. If the key is not present, it inserts a new entry with the key and a given default value, and returns the inserted value.
If the computation of the default value is expensive, consider usingMap.prototype.getOrInsertComputed() instead, which takes a callback to compute the default value only if it's actually needed.
In this article
Try it
const map = new Map([["bar", "foo"]]);console.log(map.getOrInsert("bar", "default"));// Expected output: "foo"console.log(map.getOrInsert("baz", "default"));// Expected output: "default"Syntax
getOrInsert(key, defaultValue)Parameters
keyThe key of the value to return from the
Mapobject. Object keys are compared byreference, not by value.defaultValueThe value to insert and return if the key is not already present in the
Mapobject.
Return value
The value associated with the specified key in theMap object. If the key can't be found,defaultValue is inserted and returned.
Description
ThegetOrInsert() method is equivalent to the following:
if (map.has(key)) { return map.get(key);}map.set(key, defaultValue);return defaultValue;It is also similar to the following pattern (which is slightly less reliable ifnull orundefined are valid values in your map):
map.set(key, map.get(key) ?? defaultValue);Examples
>Multimap
In a map where each key is mapped to an array of values, you can usegetOrInsert() to ensure that the array exists for a given key before attempting to push a new value to the array.
map.getOrInsert(key, []).push(value);Applying default values
You can usegetOrInsert() to ensure that a key exists in a map, even if you currently don't need its value. This is usually to normalize user input.
Imagine you have a map of user preferences, and you want to ensure that a certain preference is always set to a default value if the user hasn't specified it:
const options = readConfig();options.getOrInsert("theme", "light");options.getOrInsert("fontSize", 14);// Later in your code, you can safely assume these options existdocument.body.dataset.theme = options.get("theme");Specifications
| Specification |
|---|
| Upsert> # sec-map.prototype.getOrInsert> |