JavaScript Maps
A Map stores key–value pairs, like an object, but with important upgrades: keys can be any type (objects, numbers, functions), the insertion order is guaranteed, it knows its own size, and it's designed for frequent additions and removals.
Creating and using a Map
const prices = new Map();
prices.set("apple", 0.5);
prices.set("bread", 2.2).set("milk", 1.1); // set() is chainable
console.log(prices.get("bread"));
console.log(prices.get("cheese")); // missing -> undefined
console.log(prices.has("milk"), prices.size);
prices.delete("apple");
console.log(prices);2.2
undefined
true 3
Map(2) { 'bread' => 2.2, 'milk' => 1.1 }
You can also create a Map from an array of [key, value] pairs — or from an object with Object.entries:
const capitals = new Map([
["France", "Paris"],
["Japan", "Tokyo"],
]);
const fromObject = new Map(Object.entries({ red: "#f00", green: "#0f0" }));
console.log(capitals);
console.log(fromObject.get("green"));Map(2) { 'France' => 'Paris', 'Japan' => 'Tokyo' }
#0f0
Map methods and properties
| Member | Purpose |
|---|---|
set(key, value) |
add or update an entry; returns the map |
get(key) |
read a value (undefined if missing) |
has(key) |
check whether a key exists |
delete(key) |
remove an entry; returns true if removed |
clear() |
remove all entries |
size |
number of entries |
keys(), values(), entries() |
iterators |
forEach(fn) |
call fn(value, key) for each entry |
Any value can be a key
Object keys are always converted to strings. Map keys keep their type — 1 and "1" are different keys, and objects can be keys too:
const m = new Map();
m.set(1, "number one");
m.set("1", "string one");
console.log(m.get(1), "|", m.get("1"));
const alice = { name: "Alice" };
const bob = { name: "Bob" };
const lastSeen = new Map([
[alice, "2025-03-14"],
[bob, "2025-03-10"],
]);
console.log(lastSeen.get(alice));
const plain = {};
plain[alice] = "x"; // the key becomes "[object Object]"
console.log(Object.keys(plain));number one | string one
2025-03-14
[ '[object Object]' ]
Iterating
Maps iterate in insertion order. Each entry is a [key, value] array, so destructuring fits perfectly:
const scores = new Map([
["Lena", 88],
["Tom", 92],
["Ines", 79],
]);
for (const [name, score] of scores) {
console.log(`${name}: ${score}`);
}
console.log([...scores.keys()]);
const best = [...scores].sort((a, b) => b[1] - a[1])[0];
console.log("Top:", best[0]);
console.log(Object.fromEntries(scores)); // back to a plain objectLena: 88
Tom: 92
Ines: 79
[ 'Lena', 'Tom', 'Ines' ]
Top: Tom
{ Lena: 88, Tom: 92, Ines: 79 }
Counting with a Map
A classic use: counting occurrences.
const words = "to be or not to be that is the question".split(" ");
const counts = new Map();
for (const w of words) {
counts.set(w, (counts.get(w) ?? 0) + 1);
}
console.log(counts.get("to"), counts.get("be"), counts.get("question"));
console.log(counts.size, "distinct words");2 2 1
8 distinct words
Map or object?
Map |
Object {} |
|
|---|---|---|
| Key types | anything | strings and symbols |
| Order | insertion order | mostly insertion order (integer keys first) |
| Size | map.size |
Object.keys(obj).length |
| Iteration | directly iterable | via Object.entries() |
| Frequent add/remove | optimised | slower |
| JSON support | convert first | JSON.stringify works |
| Best for | dynamic collections, lookups by id | fixed records with known fields |
WeakMap holds object keys "weakly", letting entries disappear when the key object is garbage-collected — useful for caching data about objects without leaking memory.
Test yourself
How do you read the value for key k in a Map m?
- m[k]
- m.get(k)
- m.k
- m.read(k)
Which is a key advantage of Map over a plain object?
- Faster JSON conversion
- Keys can be any type, including objects
- It has no size limit
- It can store functions
What does iterating a Map with for…of give you?
- Keys only
- Values only
- [key, value] pairs
- Indexes