Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 156 ยท Arrays

Maps

Learn the JavaScript Map - keys of any type, insertion-order loops, converting to and from objects, and when to choose a Map, an object or a WeakMap.

You have used plain objects to store key-value data since early in this course: { apples: 3, pears: 5 }. Objects are great for describing one thing with a fixed set of properties, like a user or a product. They are less great as a general-purpose dictionary, where keys come and go at runtime, keys might not be strings, and you need to know how many entries there are.

That is the job of Map. A map is a collection of key-value pairs where the key can be any value: a string, a number, an object, even a function. It remembers insertion order, knows its own size, and has no inherited keys to trip over. In this lesson you will learn the Map API, how it differs from an object, how to loop over and convert maps, and what WeakMap is for.

Creating and using a map

Create an empty map with new Map(), or pass an array of [key, value] pairs:

JavaScript
const stock = new Map([
  ["apples", 12],
  ["pears", 0],
]);

The API mirrors the Set API, with values attached:

Member What it does
map.set(key, value) Adds or updates an entry; returns the map, so calls can be chained
map.get(key) The value for key, or undefined if there is none
map.has(key) true if the key exists
map.delete(key) Removes an entry; returns true if it existed
map.size Number of entries (a property)
map.clear() Removes every entry
JS Map basics

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

No output.

Don't use brackets with a map. stock["apples"] = 5 does not add an entry. It sets an ordinary property on the map object, which get(), size and loops all ignore. Always use set() and get().

Keys of any type

With an object, every key is turned into a string (or must be a symbol). obj[1] and obj["1"] are the same property, and using an object as a key gives you the useless key "[object Object]".

A map keeps keys exactly as they are. Keys are compared with SameValueZero, the same rule a Set uses: like ===, except that NaN matches NaN. Objects match only if they are the same object.

JS Objects as keys

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

No output.

Object keys are useful for attaching extra data to objects you don't own, such as DOM elements or objects returned by a library, without adding properties to them.

Looping over a map

Maps keep entries in insertion order. Updating an existing key keeps its position; deleting and re-adding moves it to the end. Maps are iterable, and each step gives you a [key, value] pair, which you can destructure right in the loop:

JS Iterating a map

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

No output.

Notice the argument order in forEach: the value comes first and the key second, matching array.forEach(item, index).

Converting between maps and objects

Because objects and maps both hold key-value pairs, you often convert between them. Two methods do the work, both covered in Working with Objects:

JavaScript
const settings = { theme: "dark", fontSize: 16 };

const asMap = new Map(Object.entries(settings));  // object โ†’ map
const asObject = Object.fromEntries(asMap);       // map โ†’ object

Converting a map to an object turns every key into a string, so only do it when your keys are strings (or numbers you don't mind becoming strings).

This matters for JSON. JSON.stringify(map) gives "{}", because a map has no enumerable own properties. Convert first, depending on what the receiver expects:

JavaScript
JSON.stringify(Object.fromEntries(map)); // {"theme":"dark","fontSize":16}
JSON.stringify([...map]);                // [["theme","dark"],["fontSize",16]]

The array-of-pairs form keeps non-string keys and order, and new Map(JSON.parse(text)) turns it straight back into a map. See JSON for more.

Map or object?

Both are useful. A simple rule of thumb:

Use an object for a record: a thing with a known shape, such as { id, name, email }. Property names are part of your code, you access them with dots, and it converts to JSON directly.

Use a map for a dictionary: a collection whose keys are data. That includes:

  • Keys that are not strings (objects, numbers you want to keep as numbers).
  • Keys that arrive at runtime, especially from user input. An object has inherited names such as constructor and toString, and the special key __proto__ can even change the object's prototype. A map has none of those problems.
  • Frequent adding and removing. Maps are optimized for that, while engines optimize objects for a fixed shape.
  • Needing the count (size) or a reliable order. Objects order integer-like keys numerically before other keys; maps always use insertion order.
JS A word counter with a Map

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

No output.

The pattern map.set(key, (map.get(key) ?? 0) + 1) is the map version of the counting recipe from Array Recipes. That lesson also introduced Map.groupBy(), which builds a map of arrays in one call.

Caching results with a map

A map is the natural place to remember results you already computed, a technique called memoization. The input is the key and the result is the value:

JavaScript
const cache = new Map();

function slowSquare(n) {
  if (cache.has(n)) return cache.get(n);
  const result = n * n; // imagine something expensive here
  cache.set(n, result);
  return result;
}

Wrap that in a function and you get a reusable helper; you will recognize the shape from closures and higher-order functions.

WeakMap in brief

A WeakMap is a map whose keys must be objects (or non-registered symbols), held weakly. If nothing else in your program refers to a key object, the garbage collector can delete it, and its entry vanishes from the WeakMap too. For that reason a WeakMap has only set, get, has and delete: no size, no clear and no way to loop over it.

That makes it ideal for attaching data to objects you don't control without causing memory leaks:

JavaScript
const clickCounts = new WeakMap();

function trackClick(button) {
  clickCounts.set(button, (clickCounts.get(button) ?? 0) + 1);
}

When a button is removed from the page and forgotten, its count is cleaned up automatically. With a normal Map, the map itself would keep every old button alive forever. Before classes had #private fields (see Private Fields and Static Members), WeakMap was also the standard way to give objects truly private data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? const m = new Map(); m["a"] = 1; console.log(m.size, m.get("a"));

    Bracket assignment sets a normal property on the map object. It is not an entry, so size stays 0 and get returns undefined.
  2. 2. Why might you choose a Map over a plain object?

    Maps accept any key type and have no inherited keys like constructor or __proto__, so they are safer for dynamic data.
  3. 3. In map.forEach((a, b) => ...), what are a and b?

    Like array.forEach(item, index), the value comes first and the key second. A for...of loop gives [key, value] pairs instead.
  4. 4. How do you turn the map m (with string keys) into a plain object?

    Object.fromEntries accepts any iterable of [key, value] pairs, including a map. Spreading or assigning a map copies no entries.
  5. 5. Which statement about WeakMap is true?

    A WeakMap holds its object keys weakly, so garbage collection can remove entries. That is also why it can't be iterated or counted.

Summary

  • A Map stores key-value pairs with keys of any type; use set, get, has, delete, clear and size.
  • Keys are compared like === (with NaN matching itself); objects are matched by reference.
  • Maps iterate in insertion order and yield [key, value] pairs; forEach passes the value first.
  • Convert with new Map(Object.entries(obj)) and Object.fromEntries(map); stringify a map by converting it first.
  • Use objects for records with a known shape and maps for dictionaries with dynamic keys.
  • WeakMap holds object keys weakly and is used to attach data to objects without leaking memory.

Next: WeakMap, WeakSet and WeakRef.