</>
Skip to content
JavaScript lessons (36/64)

JavaScript — Maps

A Map stores keyed data

Like objects, but designed for it:

const capitals = new Map();
capitals.set("France", "Paris");
capitals.set("Japan", "Tokyo");

capitals.get("Japan");     // "Tokyo"
capitals.has("Brazil");    // false
capitals.size;             // 2
capitals.delete("France"); // true
capitals.clear();          // empty again

Chaining works — set returns the map:

const m = new Map().set("a", 1).set("b", 2);

Map vs plain object

ObjectMap
Key typesstrings/symbols onlyanything (objects, NaN, fns)
Key ordermostly insertion (except numeric-ish)guaranteed insertion
Sizemanual (Object.keys().length).size
Iterationclunky (entries/Object.keys)directly iterable
Performancefine for static recordsbetter for constant adds/deletes

Rule of thumb: fixed record shape → object. Growing keyed dataset → Map.

Any-key superpower

const domRefs = new Map();

const btn = document.querySelector("#save");   // object as key!
domRefs.set(btn, { clicks: 0 });

btn.addEventListener("click", () => {
    const meta = domRefs.get(btn);
    meta.clicks++;
});

Attaching data to objects without polluting them — impossible cleanly with {}.

Iteration

for (const [country, city] of capitals) {   // destructures entries
    console.log(`${city}, ${country}`);
}

[...capitals.keys()];      // ["France","Japan"]
[...capitals.values()];
[...capitals.entries()];   // [["France","Paris"], …]

Convert both directions:

new Map(Object.entries({ x: 1, y: 2 }));   // obj → Map
Object.fromEntries(map);                    // Map → obj

Building from arrays & updating counts

const pairs = [["js", 1995], ["py", 1991]];
const born = new Map(pairs);

born.set("js", born.get("js") + 1);   // read-modify-write pattern

Frequency counting idiom:

const freq = new Map();
for (const w of words) {
    freq.set(w, (freq.get(w) ?? 0) + 1);
}

WeakMap (one paragraph)

Keys must be objects; entries are garbage-collectable when the key dies elsewhere. Used for private data and caching tied to object lifetimes — recognize it, don't force it.

Gotchas: map[key] = v on a Map silently does nothing useful (that's property syntax!) — always set/get. Two identical-looking object keys are still two different references.

Mini Practice

  1. Word-frequency counter over a paragraph using the get/??/set idiom
  2. Convert an object to a Map, add a key, convert back
  3. Attach click-count metadata to three buttons via element keys
  4. Iterate a Map printing "key → value" aligned with padEnd
  5. Benchmark object-vs-Map churn of 100k set/delete cycles (console.time)

Next: type conversion → (next new topic: typeof already covered — continuing errors)

Related Topics

Frequently Asked Questions about Maps

What is Maps in JavaScript?

Maps is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Maps?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Maps.

Why is Maps important in JavaScript?

Maps is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.