jsguides

Map.prototype.get()

map.get(key)

The get() method retrieves the value associated with a specified key from a Map object. If the key doesn’t exist, it returns undefined. This behavior differs subtly but importantly from plain object property access.

Syntax

map.get(key)

Parameters

ParameterTypeDefaultDescription
keyanyThe key whose value to retrieve

Return Value

The value associated with the key, or undefined if the key doesn’t exist. Unlike objects, undefined is a valid Map value—you can store undefined as a value and distinguish it from a missing key only by using has().

Examples

Basic Retrieval

const userRoles = new Map([
  ['alice', 'admin'],
  ['bob', 'editor'],
  ['charlie', 'viewer']
]);

console.log(userRoles.get('alice'));   // "admin"
console.log(userRoles.get('bob'));     // "editor"
console.log(userRoles.get('charlie')); // "viewer"

// Key doesn't exist - returns undefined
console.log(userRoles.get('dave'));    // undefined

The basic pattern is straightforward — pass a key you used with set() and get the corresponding value back. When the key is missing, get() returns undefined, which is simple but can be ambiguous when undefined might itself be a stored value. The next example shows how to handle missing keys safely with a fallback.

Handling missing keys gracefully

const config = new Map([
  ['theme', 'dark'],
  ['language', 'en']
]);

// Safe retrieval with fallback
function getConfig(key, defaultValue) {
  return config.get(key) ?? defaultValue;
}

console.log(getConfig('theme', 'light'));    // "dark" (exists)
console.log(getConfig('fontSize', '16px'));  // "16px" (fallback)

// Direct access without fallback - careful!
const timeout = config.get('timeout');
if (timeout === undefined) {
  console.log('No timeout set');  // This runs for missing keys
}

The nullish coalescing operator (??) pairs naturally with get() for providing defaults, since it only kicks in for null and undefined — not for falsy values like 0 or empty strings. That makes it a safer fallback mechanism than || when your Map might legitimately store empty strings or zeroes. Maps also accept any value as a key, including objects, which opens up patterns that plain objects simply cannot replicate.

Maps with object keys: where get() excels

This is where Maps truly shine—using objects as keys where plain objects fail:

const widgetRegistry = new Map();

const buttonWidget = { type: 'button', id: 'btn-1' };
const inputWidget = { type: 'input', id: 'inp-1' };

// Store metadata for each widget object
widgetRegistry.set(buttonWidget, { clicks: 150, shown: true });
widgetRegistry.set(inputWidget, { focusCount: 42, shown: true });

// Retrieve using the same object reference
console.log(widgetRegistry.get(buttonWidget)); 
// { clicks: 150, shown: true }

// Plain objects can't do this:
const plainObj = {};
const key = { a: 1 };
plainObj[key] = 'value';
console.log(plainObj[{ a: 1 }]); // undefined! Different object reference

Object-keyed Maps are a common pattern in UI frameworks and plugin systems, where each component or module needs its own private metadata slot. The key is the object itself — no need to invent string IDs or maintain a separate lookup table. However, when you need to distinguish “key exists with value undefined” from “key does not exist,” get() alone is not enough. The has() method fills that gap.

The has() + get() Pattern

For non-trivial logic, always check with has() before retrieving:

const cache = new Map();

function getUserData(userId) {
  // Check existence first - critical for falsy but valid values!
  if (!cache.has(userId)) {
    // Simulate fetching from database
    const freshData = fetchFromDB(userId);
    cache.set(userId, freshData);
  }
  
  // Now safe to get
  return cache.get(userId);
}

// Why has() matters: distinguishing undefined value from missing key
const settings = new Map();
settings.set('debug', undefined);

console.log(settings.get('debug')); // undefined
console.log(settings.has('debug')); // true - key exists!

console.log(settings.get('missing')); // undefined  
console.log(settings.has('missing')); // false - key doesn't exist

Map.get() vs object property access

Aspectmap.get(key)obj[key] or obj.key
Key typesAny value (objects, functions, primitives)Strings/symbols only
Missing keyReturns undefinedReturns undefined
Prototype pollutionImmuneInherits from prototype
OrderMaintains insertion orderNot guaranteed
Sizemap.size (O(1))Object.keys(obj).length (O(n))

Performance Note

Map.get() runs in O(1) average time — constant regardless of how many entries the Map contains. This makes it considerably faster than searching an array for a matching value with find() or findIndex(), which are O(n). For lookup-heavy code (caches, registries, configuration stores), a Map is almost always the right choice over an array of objects. Object property access is also O(1), but Map performs better when keys are not strings or when the number of entries is large and changes frequently.

get() with object keys

When using objects as keys, get() uses reference equality — the same object reference that was passed to set(). A structurally identical but different object returns undefined:

const map = new Map();
const key = { id: 1 };
map.set(key, "value");

map.get(key);              // "value" — same reference
map.get({ id: 1 });        // undefined — different object, same shape

This is the intended behavior: object identity as a key is a feature that plain objects cannot replicate.

When to Pair get() With has()

get() is easy to read, but it becomes ambiguous when undefined is a valid stored value. In that case, pairing it with has() tells you whether a missing key or a real undefined value is present. That distinction matters in caches, configuration, and feature flags where “not set” and “set to empty” are not the same thing. The combination is small, but it prevents subtle bugs that are hard to spot later.

See Also