JavaScript lesson · 17 min
JavaScript Map
Store key-value pairs and count repeated values without awkward object tricks.
What you will practice
- Create a Map.
- Store and update values by key.
- Count repeated items in a list.
What this means
A Map stores key-value pairs. A key points to a value, similar to how a label points to a box.
Objects can also store key-value data, but Map is designed for collections that change while the program runs.
Map has clear methods: `set` to write, `get` to read, `has` to check, and `size` to count keys.
If this is your first time seeing this
Map is for key-value collections that grow or change while the program runs.
It is especially handy for counters, lookup tables, and caches.
Mini glossary
- Map
- A collection of key-value pairs.
- key
- The lookup value used to find an entry.
- value
- The data stored under a key.
Example from everyday life
A Map is like a scoreboard. Each player name is a key, and the score beside it is the value. When someone scores again, you update their existing number instead of writing a new row.
How it works step by step
- The code starts with an array of tool categories.
- It creates an empty Map named `counts`.
- The loop reads the old count for each category, or uses 0 if the category has not appeared yet.
- `counts.set(category, current + 1)` writes the updated count back into the Map.
Where you will use this
- Analytics code counts how often each tool is used.
- A text analyzer counts word frequency.
- A build tool maps file paths to metadata.
Before you run the code
Map is useful when your keys are dynamic and you are adding, updating, or reading entries often.
For simple fixed records like a user profile, an object is often clearer. For a changing collection of key-value pairs, Map is a strong choice.
Common beginner mistakes
- Using `map.key` instead of `map.get("key")`.
- Forgetting that missing keys return `undefined`.
- Using Map for a simple fixed object where an object would be easier to read.
Run the code to see console output here.
Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Add another category to the array.
- Print `counts.has("seo")`.
- Loop over `counts` and print every key-value pair.