Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. Map
  6. getOrInsert()

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.

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

js
getOrInsert(key, defaultValue)

Parameters

key

The key of the value to return from theMap object. Object keys are compared byreference, not by value.

defaultValue

The value to insert and return if the key is not already present in theMap object.

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:

js
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):

js
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.

js
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:

js
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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp