Creating a Map
A Map holds key-value pairs where keys can be any type (not just strings).
const map = new Map();
map.set("name", "Alice");
map.set(42, "the answer");
map.set(true, "boolean key");
console.log(map.size); // 3
Try it Yourself →
get, has, and delete
Retrieve values with get, check existence with has, remove with delete.
const scores = new Map();
scores.set("Alice", 95);
scores.set("Bob", 87);
scores.set("Charlie", 92);
console.log(scores.get("Alice")); // 95
console.log(scores.has("Bob")); // true
scores.delete("Charlie");
console.log(scores.size); // 2
Iterating a Map
Maps preserve insertion order. Use forEach or for...of to iterate.
const colors = new Map([
["R", "Red"],
["G", "Green"],
["B", "Blue"]
]);
colors.forEach((value, key) => {
console.log(key + ": " + value);
});
for (const [key, value] of colors) {
console.log(key + " -> " + value);
}
Map vs Object
Maps excel when keys are dynamic, non-string, or when you need to frequently add/delete entries.
const obj = {};
const map = new Map();
const keyObj = { id: 1 };
obj[keyObj] = "lost"; // becomes obj["[object Object]"]
map.set(keyObj, "found");
console.log(obj["[object Object]"]); // "lost"
console.log(map.get(keyObj)); // "found"
console.log(obj.constructor); // shows object prototype
console.log(map.size); // better than Object.keys(obj).length