๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Maps

A Map is a collection that stores pairs of keys and values. Each key points to one value.

Store and read pairs

set stores each price under a fruit name. get reads one price back.

const prices = new Map();
prices.set("Apple", 3);
prices.set("Pear", 4);
console.log(prices.get("Apple"));

Replace a value

The same key is set twice. The second value wins, and the size stays at one.

const scores = new Map();
scores.set("Ana", 10);
scores.set("Ana", 14);
console.log(scores.get("Ana"));
console.log(scores.size);

Number keys

Numbers work as keys in a Map. has and size report on the stored pairs.

const codes = new Map();
codes.set(1, "One");
codes.set(2, "Two");
console.log(codes.has(2));
console.log(codes.has(3));
console.log(codes.size);

Example

const words = ["cat", "dog", "cat", "bird", "dog", "cat"];
const counts = new Map();
words.forEach(word => {
  counts.set(word, (counts.get(word) || 0) + 1);
});
console.log(counts.get("cat"));
console.log(counts.get("dog"));
console.log(counts.size);

Key points

  • set stores a value under a key.
  • get returns the value stored under a key.
  • Setting an existing key replaces its value.
  • Replacing a value does not change the size.
  • has returns true when the key is present.
  • Keys can be any value, such as a string or a number.
  • The size property reports how many pairs the map holds.

In this example, forEach visits each word in the array. The count for a new word starts at zero and grows by one per visit. The map ends with three keys, and cat holds the count three.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What happens when set is called with a key that the Map already holds?