Map.prototype.get
Returns the value for a key.
Available since: ES2015
Syntax
map.get(key)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | any | The key. |
Return value
anyThe value, or undefined if the key is missing.
Examples
An existing and a missing key:
const capitals = new Map([['France', 'Paris']]);
console.log(capitals.get('France'));
console.log(capitals.get('Spain'));Output:
Paris
undefinedA default value:
const capitals = new Map([['France', 'Paris']]);
console.log(capitals.get('Spain') ?? 'unknown');Output:
unknownNotes
Square brackets do not work with a Map: capitals['France'] returns undefined. Always use get().
See also
- Map.prototype.set — Adds or replaces the value for a key.
- Map.prototype.has — Checks whether a key is in a Map.
- Nullish coalescing (??) — Returns the right-hand value if the left is null or undefined.
In the tutorial
- Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.