Sikau

Advanced JavaScript · Day 11 · about 25 min

Map

A dictionary with any kind of key.

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.

The rest of this lesson

  • Map or plain object?explain
  • Predict the outputpredict
  • Objects as keyspredict
  • Map methodsmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript