iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Maps

A Map is a key-value collection — like a plain object, but with two advantages: any value can be a key, and iteration order is guaranteed insertion order.

Map vs. plain object

MapObject
Key typesAnything — strings, numbers, objects, functionsStrings & symbols
Sizemap.sizeNo direct way
IterationInsertion order, built-inOrder ish; need Object.keys
PrototypeNo inherited keys to worry abouttoString, hasOwnProperty, etc.
Use it forDynamic, frequent add/delete, non-string keysStatic records, JSON shapes

Usage

JS
const users = new Map();
users.set(1, { name: "Ada" });
users.set(2, { name: "Grace" });

users.get(1);            // { name: "Ada" }
users.has(2);            // true
users.delete(1);
users.size;              // 1

// Initialize from key-value pairs
const m = new Map([
  ["one", 1],
  ["two", 2],
]);

// Iterate
for (const [k, v] of m) console.log(k, v);
m.forEach((v, k) => console.log(k, v));

Object keys you can't have with plain objects

JS
const cache = new Map();
const reqA = { url: "/a" };
const reqB = { url: "/b" };

cache.set(reqA, "responseA");   // ← object as key
cache.get(reqA);                // "responseA"

Convert between Map and Object

JS
const obj = Object.fromEntries(map);
const map = new Map(Object.entries(obj));
Tip: Reach for Map any time the keys are dynamic or non-string. For static "data shapes" you'd serialize to JSON, stick with plain objects.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Maps!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Get the number of entries in a Map.

const count = map. ;

Test yourself

Q1. A Map differs from a plain object because…
Q2. Get the number of entries with…
Q3. Convert a Map to a plain object with…

Discussion

Loading…