Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Collections

Map.prototype.get() and set()

Reference for Map.prototype.get() and set(): read a value by key, add or update an entry, chain calls, and tell a missing key from an undefined value.

map.set(key, value) stores a value under a key and returns the map itself, so calls can be chained. map.get(key) returns the value stored under a key, or undefined when the key is not in the map.

If the key already exists, set() replaces the value but leaves the key at its original position in the iteration order. A new key is added at the end.

JavaScript
const scores = new Map();
scores.set("Ada", 10).set("Linus", 7);
scores.get("Ada");     // 10
scores.get("Grace");   // undefined

Try it

JS Setting, updating and chaining

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Missing keys and object keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
map.get(key)
map.set(key, value)
Method Name Description
get() key The key to look up. Compared with "same value zero" (like ===, but NaN equals NaN).
set() key The key to store. Any value is allowed.
set() value The value to store. Any value is allowed, including undefined.

Return value: get() returns the stored value, or undefined if the key is absent. set() returns the map.

Exceptions: none for ordinary use. Calling the methods on something that is not a Map throws a TypeError.

Usage notes

  • get() cannot tell "missing" from "stored undefined". When a map may hold undefined values, check with has() first.
  • Use ?? for a default, as in map.get(k) ?? 0. Use || only if falsy stored values such as 0 or "" should also be replaced.
  • Updating keeps the position. set() on an existing key does not move it. To move a key to the end, delete() it first.
  • Object keys use identity. Two objects with equal contents are different keys. Keep a reference to the original object to read the entry back.
  • Mutable values are not copied. map.get(k) returns the stored array or object itself, so changing it changes what is in the map. That is handy for grouping: (groups.get(k) ?? groups.set(k, []).get(k)).push(item).
  • No bracket syntax. map["key"] = 1 sets an ordinary property on the map object and does not create an entry. Always use set() and get().
  • Newer helpers. Proposals add getOrInsert() and getOrInsertComputed() for the "get or create" pattern. They are recent, so check a compatibility table before using them.

Browser support

get() and set() work in every current browser and in Node.js. getOrInsert() and getOrInsertComputed() are new and not available everywhere.