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
| Map | Object | |
|---|---|---|
| Key types | Anything — strings, numbers, objects, functions | Strings & symbols |
| Size | map.size | No direct way |
| Iteration | Insertion order, built-in | Order ish; need Object.keys |
| Prototype | No inherited keys to worry about | toString, hasOwnProperty, etc. |
| Use it for | Dynamic, frequent add/delete, non-string keys | Static 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.
;
Four letters — not `length`.
Discussion
Loading…