JavaScript lesson · 17 min

JavaScript Map

Store key-value pairs and count repeated values without awkward object tricks.

Code runs locally in your browser

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

  1. The code starts with an array of tool categories.
  2. It creates an empty Map named `counts`.
  3. The loop reads the old count for each category, or uses 0 if the category has not appeared yet.
  4. `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 in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingCounts repeated category values
WaitingTracks the number of keys

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.