Learn JavaScript · lesson 57 of 60 · about 8 minutes
Map
Store key-value pairs where the key can be anything, and count things easily.
What you'll learn
- Create a Map and use set, get and has
- Loop over a Map's entries
- Count items with a Map
Where visitors come from
Sam's page now asks visitors which town they're visiting from, and visitorTowns holds what they typed, one entry for each visit. Sam wants to count them, 6 visits from 3 towns: Leeds 3, York 2, Paris 1, and to see how many came from Sam's own town, as Visits from Leeds: 3. Counting is exactly what a Map is good at: each town is a key, and its value is how many visits it has.
A dedicated dictionary
Objects can store key-value pairs, but their keys are always text. A Map is built for the job: keys can be any type, it remembers the order you added them, and it knows its own size.
map.set(key, value) stores a pair, map.get(key) reads it back, and map.has(key) checks whether the key is there.
Using a Map
const stock = new Map();
stock.set("tea", 12);
stock.set("cake", 3);
stock.set(42, "the answer");
console.log(stock.get("tea"));
console.log(stock.get(42));
console.log(stock.has("milk"), stock.size);Output
12
the answer
false 3Counting and looping
To count things, get the old count (or 0 if it's missing) and set it one higher. for (const [key, value] of map) then loops over every pair in the order they were added.
Counting votes
const votes = ["red", "blue", "red", "green", "red"];
const counts = new Map();
for (const v of votes) {
counts.set(v, (counts.get(v) ?? 0) + 1);
}
for (const [colour, n] of counts) {
console.log(colour, n);
}Output
red 3
blue 1
green 1Counting the towns
Each typed town is trimmed first, so Leeds counts as Leeds, and an empty one is skipped. Then townCounts.set(name, (townCounts.get(name) ?? 0) + 1) adds one to that town's count, starting from 0 the first time. The Map remembers the order the towns first appeared, so [...townCounts] lists Leeds before York, and townCounts.size is how many different towns there were. townCounts.get(town) ?? 0 gives Sam's own town's count, or 0 if nobody came from there.
Tip
map.delete(key) removes a pair, and new Map([["a", 1], ["b", 2]]) builds a Map from pairs in one go.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.