Skip to content

JavaScript Tutorial Map, Set and Other Collections

JavaScript Map

Lesson 185 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

A Map is a collection of key-value pairs, like an object, but with more flexibility.

script.js
JS
const ages = new Map();

ages.set("Maya", 28);
ages.set("Arjun", 31);

console.log(ages.get("Maya"));   // → 28
console.log(ages.has("Sam"));    // → false
console.log(ages.size);          // → 2

ages.delete("Arjun");
console.log(ages.size);          // → 1
Method / propertyDoes
set(key, value)adds or updates (returns the map, so it can be chained)
get(key)the value, or undefined
has(key)does the key exist?
delete(key)removes it
clear()removes everything
sizethe number of entries

Create from entries

script.js
JS
const prices = new Map([
  ["tea", 3],
  ["coffee", 4]
]);

console.log(prices.get("coffee")); // → 4

Any value can be a key

Objects always turn keys into strings. A Map keeps the real key, including objects and functions.

script.js
JS
const user1 = { name: "Maya" };
const user2 = { name: "Arjun" };

const visits = new Map();
visits.set(user1, 3);
visits.set(user2, 7);

console.log(visits.get(user1)); // → 3
console.log(visits.get({ name: "Maya" })); // → undefined (a different object)

Looping

Entries are kept in insertion order, and a Map is iterable.

script.js
JS
const prices = new Map([["tea", 3], ["coffee", 4]]);

for (const [item, price] of prices) {
  console.log(item, price);
}

console.log([...prices.keys()]);    // → ["tea", "coffee"]
console.log([...prices.values()]);  // → [3, 4]

prices.forEach((price, item) => console.log(item + ": " + price));

Converting

script.js
JS
const map = new Map([["a", 1], ["b", 2]]);

console.log(Object.fromEntries(map));           // → { a: 1, b: 2 }
console.log(new Map(Object.entries({ x: 9 })));  // → Map(1) { 'x' => 9 }
console.log([...map]);                           // → [["a", 1], ["b", 2]]

A counting example

script.js
JS
const words = ["a", "b", "a", "c", "a"];
const counts = new Map();

for (const word of words) {
  counts.set(word, (counts.get(word) ?? 0) + 1);
}

console.log(counts); // → Map(3) { 'a' => 3, 'b' => 1, 'c' => 1 }

Key equality

Maps compare keys with the “same value zero” rule: like ===, but NaN equals NaN.

JSON

Maps do not turn into JSON by default: JSON.stringify(new Map()) is {}. Convert to an object or array first.

info
Next
See When to Use Map Instead of Object to choose between them.