Better than an object for lookups
Objects work as dictionaries, but their keys are always strings, they inherit stray properties, and counting their size is awkward. A Map is built for key → value lookups, with any type of key.
Using a Map
const prices = new Map();
prices.set("momo", 180);
prices.set("chiya", 40);
console.log(prices.get("momo"));
console.log(prices.has("lassi"), prices.size);
prices.delete("chiya");
const stock = new Map([["rice", 20], ["dal", 8]]);
for (const [item, qty] of stock) {
console.log(item, qty);
}
console.log([...stock.keys()]);const visits = new Map();
const asha = { name: "Asha" };
visits.set(asha, 3);
console.log(visits.get(asha));
const counts = new Map();
for (const w of ["a", "b", "a"]) {
counts.set(w, (counts.get(w) ?? 0) + 1);
}
console.log(Object.fromEntries(counts));A WeakMap only takes object keys and lets them be garbage-collected when nothing else uses them — perfect for caching data about objects without leaking memory.