A Map is a collection of key-value pairs, like an object, but with more flexibility.
const ages = new Map();
ages.set("Maya", 28);
ages.set("Arjun", 31);
console.log(ages.get("Maya")); // → 28
console.log(ages.has("Sam")); // → false
console.log(ages.size); // → 2
ages.delete("Arjun");
console.log(ages.size); // → 1
| Method / property | Does |
|---|---|
set(key, value) | adds or updates (returns the map, so it can be chained) |
get(key) | the value, or undefined |
has(key) | does the key exist? |
delete(key) | removes it |
clear() | removes everything |
size | the number of entries |
Create from entries
const prices = new Map([
["tea", 3],
["coffee", 4]
]);
console.log(prices.get("coffee")); // → 4
Any value can be a key
Objects always turn keys into strings. A Map keeps the real key, including objects and functions.
const user1 = { name: "Maya" };
const user2 = { name: "Arjun" };
const visits = new Map();
visits.set(user1, 3);
visits.set(user2, 7);
console.log(visits.get(user1)); // → 3
console.log(visits.get({ name: "Maya" })); // → undefined (a different object)
Looping
Entries are kept in insertion order, and a Map is iterable.
const prices = new Map([["tea", 3], ["coffee", 4]]);
for (const [item, price] of prices) {
console.log(item, price);
}
console.log([...prices.keys()]); // → ["tea", "coffee"]
console.log([...prices.values()]); // → [3, 4]
prices.forEach((price, item) => console.log(item + ": " + price));
Converting
const map = new Map([["a", 1], ["b", 2]]);
console.log(Object.fromEntries(map)); // → { a: 1, b: 2 }
console.log(new Map(Object.entries({ x: 9 }))); // → Map(1) { 'x' => 9 }
console.log([...map]); // → [["a", 1], ["b", 2]]
A counting example
const words = ["a", "b", "a", "c", "a"];
const counts = new Map();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts); // → Map(3) { 'a' => 3, 'b' => 1, 'c' => 1 }
Key equality
Maps compare keys with the “same value zero” rule: like ===, but NaN equals NaN.
JSON
Maps do not turn into JSON by default: JSON.stringify(new Map()) is {}. Convert to an object or array first.