A Map is like an object (it stores key-value pairs), but with some upgrades:
- Keys can be any type: numbers, objects, even functions. (Object keys are always turned into strings.)
- It remembers the order you added things in.
- It has a built-in
size. - It's designed for adding and removing entries frequently.
const stock = new Map();
stock.set("rice", 25);
stock.set("beans", 12);
stock.set("flour", 40);
console.log(stock.get("beans"));
console.log(stock.has("sugar"));
console.log(stock.size);
stock.set("beans", 11); // update
stock.delete("flour");
for (const [item, count] of stock) {
console.log(`${item}: ${count} bags`);
}
It prints
12 false 3 rice: 25 bags beans: 11 bags
| Method / property | What it does |
|---|---|
map.set(key, value) | Adds or updates an entry |
map.get(key) | Gets a value (or undefined) |
map.has(key) | true if the key exists |
map.delete(key) | Removes an entry |
map.size | How many entries |
TipObject or Map?
For describing one thing with known properties (a user, a product, settings), use a plain object. For a collection that you'll add to and remove from a lot, especially with keys you don't know in advance, a Map is often the better tool. When in doubt, start with an object. It's simpler, and it works with JSON.stringify, which Maps don't.