Maps

Updated · 8 min read

A Map is a built-in collection of key-value pairs where the keys can be any type: strings, numbers, objects, even functions. It looks like a plain object used as a dictionary, but it was designed for that job: it has a size, keeps keys in insertion order, never collides with inherited property names, and is faster when entries are added and removed often. ES2026 adds getOrInsert and getOrInsertComputed, which make the common "get it, or create it if missing" pattern one call.

In One Minute

  • Create with new Map() or new Map([[key, value], ...]).
  • set(key, value), get(key), has(key), delete(key), clear() and size.
  • Keys keep their type: 1 and "1" are different keys, and objects can be keys.
  • Iterate with for (const [key, value] of map); order is insertion order.
  • map.getOrInsert(key, value) (ES2026) returns the existing value or stores and returns the new one.

Creating and Using a Map

Syntax

syntax.js
const map = new Map();
const map2 = new Map([[key1, value1], [key2, value2]]);

Example

basics.js▶ Try it
const balances = new Map([
  ["Navika", 450],
  ["Srihitha", 85],
]);
 
balances.set("Advitha", 45);
balances.set("Navika", 250);
 
console.log(balances.get("Navika"));
console.log(balances.get("Zoe"));
console.log(balances.has("Srihitha"), balances.size);
 
balances.delete("Srihitha");
console.log(balances);
Output
250
undefined
true 3
Map(2) {'Navika' => 250, 'Advitha' => 45}

Explanation: set adds a new key or replaces the value of an existing one (Navika's 450 became 250, and she kept her original position). get returns undefined for a missing key. set returns the map itself, so calls can be chained: map.set(a, 1).set(b, 2).

Map Methods

MethodDescription
set(key, value)It is used to add or update an entry; returns the map.
get(key)It is used to read a value, or undefined if the key is missing.
has(key)It is used to check whether a key exists.
delete(key)It is used to remove an entry; returns true if it existed.
clear()It is used to remove every entry.
sizeA property holding the number of entries.
keys(), values(), entries()It is used to get iterators over keys, values or [key, value] pairs.
forEach(fn)It is used to run fn(value, key) for each entry.
getOrInsert(key, value)It is used to get the value, or store value first if the key is missing (ES2026).
getOrInsertComputed(key, fn)Like getOrInsert, but calls fn(key) to create the value only when needed (ES2026).
Map.groupBy(items, fn)It is used to group items into a Map (ES2024).

Any Type of Key

Plain objects convert every key to a string. Maps keep keys exactly as they are:

keys.js▶ Try it
const obj = {};
obj[1] = "number one";
obj["1"] = "string one";
console.log(Object.keys(obj));
 
const map = new Map();
map.set(1, "number one");
map.set("1", "string one");
console.log(map.size, map.get(1), map.get("1"));
 
const navika = { name: "Navika" };
const notes = new Map([[navika, "Pays by check"]]);
console.log(notes.get(navika));
console.log(notes.get({ name: "Navika" }));
Output
['1']
2 number one string one
Pays by check
undefined

Explanation: in the object, obj[1] and obj["1"] are the same property, so the second assignment overwrote the first. The Map keeps both. With an object as a key, the Map looks it up by reference: the same navika object finds the note, but a different object with the same contents doesn't. That lets you attach extra data to objects you don't own, without adding properties to them.

Iterating a Map

iterate.js▶ Try it
const feesByGrade = new Map([[9, 400], [10, 415], [11, 430]]);
 
for (const [grade, fee] of feesByGrade) {
  console.log(`Grade ${grade}: $${fee}`);
}
 
console.log([...feesByGrade.keys()]);
console.log([...feesByGrade.values()].reduce((a, b) => a + b, 0));
console.log(Object.fromEntries(feesByGrade));
console.log(new Map(Object.entries({ a: 1 })));
Output
Grade 9: $400
Grade 10: $415
Grade 11: $430
[9, 10, 11]
1245
{ 9: 400, 10: 415, 11: 430 }
Map(1) {'a' => 1}

A Map iterates in insertion order, for every key type (objects reorder integer-like keys; Maps never do). Object.fromEntries(map) converts a Map to a plain object (keys become strings), and new Map(Object.entries(obj)) goes the other way.

Map vs Object

MapPlain object
Key typesAny valueStrings and symbols only
OrderInsertion order, alwaysInteger-like keys first, then insertion order
Sizemap.sizeObject.keys(obj).length
Inherited keysNoneInherits toString, constructor and others
IterationDirectly with for...ofThrough Object.entries
Frequent add and deleteOptimized for itSlower
JSONNot directly (convert first)JSON.stringify works
Best forDictionaries with dynamic keys, caches, countingFixed-shape records (a student, a payment)

Counting and Grouping

Counting occurrences is a classic Map job:

count.js▶ Try it
const methods = ["card", "check", "card", "ach", "card", "check"];
const counts = new Map();
 
for (const m of methods) {
  counts.set(m, (counts.get(m) ?? 0) + 1);
}
console.log(counts);
 
const byGrade = Map.groupBy(
  [{ name: "Navika", grade: 9 }, { name: "Srihitha", grade: 11 }, { name: "Advitha", grade: 9 }],
  (s) => s.grade
);
console.log(byGrade.get(9).map((s) => s.name));
Output
Map(3) {'card' => 3, 'check' => 2, 'ach' => 1}
['Navika', 'Advitha']

Map.groupBy (ES2024) keeps the grade as a number key, unlike Object.groupBy, which would turn it into the string "9".

getOrInsert and getOrInsertComputed (ES2026)

A very common pattern is "get the value for this key; if there isn't one yet, create it, store it, and use it". Before ES2026 it took several lines. getOrInsert and getOrInsertComputed do it in one:

get-or-insert.js▶ Try it
const paymentsByStudent = new Map();
const payments = [["Navika", 120], ["Advitha", 45], ["Navika", 60]];
 
for (const [name, amount] of payments) {
  paymentsByStudent.getOrInsert(name, []).push(amount);
}
console.log(paymentsByStudent);
 
const cache = new Map();
const slowLabel = (grade) => {
  console.log(`  computing label for ${grade}`);
  return `Grade ${grade}`;
};
console.log(cache.getOrInsertComputed(9, slowLabel));
console.log(cache.getOrInsertComputed(9, slowLabel));
Output
Map(2) {'Navika' => [120, 60], 'Advitha' => [45]}
  computing label for 9
Grade 9
Grade 9

Explanation: getOrInsert(name, []) returns the existing array for a student, or stores a new empty array and returns it, so push always has an array to work on. getOrInsertComputed takes a function and calls it only when the key is missing: the second call found the cached label and didn't recompute. Use the computed version when creating the value is expensive or has side effects, because getOrInsert(key, value) evaluates value every time, even when it isn't needed.

Before ES2026ES2026
if (!map.has(k)) map.set(k, []); map.get(k).push(x);map.getOrInsert(k, []).push(x);

In Practice

The Fee Tracker caches each student's computed balance in a Map keyed by student object, so the same object always maps to its balance, and clears the entry when a payment arrives:

cache.js▶ Try it
const balanceCache = new Map();
let computations = 0;
 
function balanceOf(student) {
  return balanceCache.getOrInsertComputed(student, (s) => {
    computations++;
    return s.fees.reduce((a, b) => a + b, 0) - s.paid.reduce((a, b) => a + b, 0);
  });
}
 
const navika = { name: "Navika", fees: [400, 85], paid: [200] };
console.log(balanceOf(navika), balanceOf(navika), computations);
 
navika.paid.push(100);
balanceCache.delete(navika);
console.log(balanceOf(navika), computations);
Output
285 285 1
185 2

Common Mistakes

Using bracket notation on a Map. map["Navika"] = 450 sets an ordinary property on the Map object, not an entry: get, has and size won't see it. Use set and get.

Expecting object keys to match by contents. Keys are compared by reference (SameValueZero).

Calling JSON.stringify(map). It gives {}. Convert first: JSON.stringify(Object.fromEntries(map)) (string keys) or JSON.stringify([...map]) (any keys).

Using getOrInsert with an expensive value. The value expression runs every time. Use getOrInsertComputed.

Interview Corner

When would you use a Map instead of an object?

When keys aren't fixed identifiers: user-supplied or dynamic keys, non-string keys (numbers that must stay numbers, objects, DOM nodes), frequent insertion and deletion, or when you need reliable insertion order and an O(1) size. Objects are better for fixed-shape records and for JSON.

How does a Map compare keys?

With SameValueZero: like ===, except NaN equals NaN. Objects are matched by identity, so two structurally identical objects are different keys.

Practice

Challenge: Write wordCounts(text) that returns a Map of each lowercase word to the number of times it appears (use get with ??), then print the most common word.

Show solution
word-counts.js▶ Try it
function wordCounts(text) {
  const counts = new Map();
  for (const word of text.toLowerCase().match(/[a-z]+/g) ?? []) {
    counts.set(word, (counts.get(word) ?? 0) + 1);
  }
  return counts;
}
 
const counts = wordCounts("Late fee, late notice, LATE again; fee waived.");
console.log(counts);
const [topWord, topCount] = [...counts].toSorted((a, b) => b[1] - a[1])[0];
console.log(topWord, topCount);
Output
Map(5) {'late' => 3, 'fee' => 2, 'notice' => 1, 'again' => 1, 'waived' => 1}
late 3

Quick check: Maps

3 questions
1What does new Map([[1, "a"]]).get("1") return?
2How do you get the number of entries in a Map?
3What does map.getOrInsertComputed(key, fn) do when key already exists?

Key Takeaways

TaskCode
Createnew Map([["a", 1]])
Add / readm.set(k, v), m.get(k)
Countm.set(k, (m.get(k) ?? 0) + 1)
Get or createm.getOrInsert(k, [])
To objectObject.fromEntries(m)

Was this tutorial helpful?

Lesson 48 of 139