Maps: Flexible Key-Value Pairs

Grade 13, page 9 of 12. A one-minute read.

A Map is like an object (it stores key-value pairs), but with some upgrades:

  • Keys can be any type: numbers, objects, even functions. (Object keys are always turned into strings.)
  • It remembers the order you added things in.
  • It has a built-in size.
  • It's designed for adding and removing entries frequently.
JavaScript
const stock = new Map();

stock.set("rice", 25);
stock.set("beans", 12);
stock.set("flour", 40);

console.log(stock.get("beans"));
console.log(stock.has("sugar"));
console.log(stock.size);

stock.set("beans", 11); // update
stock.delete("flour");

for (const [item, count] of stock) {
  console.log(`${item}: ${count} bags`);
}

It prints

12
false
3
rice: 25 bags
beans: 11 bags
Method / propertyWhat it does
map.set(key, value)Adds or updates an entry
map.get(key)Gets a value (or undefined)
map.has(key)true if the key exists
map.delete(key)Removes an entry
map.sizeHow many entries
TipObject or Map?

For describing one thing with known properties (a user, a product, settings), use a plain object. For a collection that you'll add to and remove from a lot, especially with keys you don't know in advance, a Map is often the better tool. When in doubt, start with an object. It's simpler, and it works with JSON.stringify, which Maps don't.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning