Table of Contents

Introduction

JavaScript Map object is a built-in collection that stores data as key-value pairs. Each key is unique and can be associated with a value of any JavaScript data type. Unlike regular objects, a Map can use objects, functions, numbers, and other values as keys. It also preserves the insertion order of its entries, making it useful for managing and iterating over data.

Maps are commonly used for lookup tables, caching, counting values, and managing relationships between items.

How to Create a Map

You can create an empty Map by calling the Map() constructor with the new keyword:

const myMap = new Map();

console.log(myMap); // Map(0) {}

You can also initialize a Map with an iterable containing key-value pairs. Each inner pair must contain a key followed by its value:

const userMap = new Map([
  ["name", "Sadia"],
  ["age", 25],
  ["country", "Bangladesh"]
]);

console.log(userMap.get("name")); // Sadia
console.log(userMap.get("age")); // 25

This approach is convenient when the initial data is already available. The outer array is an iterable, and each inner array represents one entry.

JavaScript Map set() Method

The set() method adds a new key-value pair to a Map or updates the value associated with an existing key. It returns the Map itself, so multiple calls can be chained.

Syntax:

map.set(key, value);

Example:

const products = new Map();

products.set("P101", "Laptop");
products.set("P102", "Keyboard");
products.set("P103", "Mouse");

console.log(products);

You can chain calls because each set() call returns the same Map:

const scores = new Map()
  .set("Rahim", 85)
  .set("Karim", 92)
  .set("Nadia", 88);

console.log(scores.get("Karim")); // 92

When a key is already present, set() updates its value instead of creating a duplicate key:

const settings = new Map();

settings.set("theme", "light");
settings.set("theme", "dark");

console.log(settings.get("theme")); // dark
console.log(settings.size); // 1

JavaScript Map get() Method

The get() method returns the value associated with a specified key. If the key does not exist, it returns undefined.

const student = new Map([
  ["name", "Arif"],
  ["grade", "A"],
  ["score", 91]
]);

console.log(student.get("name"));  // Arif
console.log(student.get("score")); // 91
console.log(student.get("email")); // undefined

Use the same key value that was inserted. Map does not automatically convert a numeric key into a string key, so 1 and "1" are different keys.

const data = new Map();

data.set(1, "Number key");
data.set("1", "String key");

console.log(data.get(1));   // Number key
console.log(data.get("1")); // String key

JavaScript Map has() Method

The has() method checks whether a specified key exists in a Map. It returns true when the key is present and false otherwise.

const account = new Map([
  ["username", "learnersedu"],
  ["active", true]
]);

console.log(account.has("username")); // true
console.log(account.has("password")); // false

This method is useful when you need to distinguish between a missing key and a key whose stored value is actually undefined.

JavaScript Map delete() Method

The delete() method removes an entry using its key. It returns true if an entry was removed and false if the key was not found.

const cart = new Map([
  ["book", 2],
  ["pen", 5],
  ["notebook", 1]
]);

const removed = cart.delete("pen");

console.log(removed); // true
console.log(cart.has("pen")); // false
console.log(cart.size); // 2

Only the entry associated with the supplied key is removed. Other entries remain in the Map.

JavaScript Map clear() Method

The clear() method removes all key-value pairs from a Map. It changes the existing Map and does not return a new collection.

const cache = new Map([
  ["home", "/"],
  ["about", "/about"],
  ["contact", "/contact"]
]);

cache.clear();

console.log(cache.size); // 0

Use clear() when you need to reset a collection completely, such as clearing an in-memory cache or resetting temporary application state.

JavaScript Map size Property

The size property returns the number of entries currently stored in a Map. It is a property, not a method, so you should not add parentheses.

const languages = new Map();

languages.set("js", "JavaScript");
languages.set("py", "Python");
languages.set("ts", "TypeScript");

console.log(languages.size); // 3

languages.delete("py");

console.log(languages.size); // 2

The value changes automatically when entries are added or removed.

How to Iterate Over a Map

Map is iterable, so you can use several approaches to read its entries. The most common options are for...of, forEach(), keys(), values(), and entries().

Using for…of

A for...of loop returns each Map entry as a two-item array containing the key and value:

const capitals = new Map([
  ["Bangladesh", "Dhaka"],
  ["Japan", "Tokyo"],
  ["France", "Paris"]
]);

for (const [country, capital] of capitals) {
  console.log(country, capital);
}

Array destructuring makes it easy to assign the key and value to separate variables. This is a readable approach when you need to process every entry.

Using forEach()

The forEach() method executes a callback once for each entry. Its callback receives the value first, the key second, and the Map itself third:

const prices = new Map([
  ["Book", 250],
  ["Bag", 1200],
  ["Pen", 20]
]);

prices.forEach((value, key) => {
  console.log(key + ": " + value);
});

Notice that the callback argument order is value followed by key, which is different from the key-value order returned by a for...of loop.

Using keys()

The keys() method returns a Map iterator containing all keys in insertion order:

const user = new Map([
  ["id", 15],
  ["name", "Mina"],
  ["role", "Editor"]
]);

for (const key of user.keys()) {
  console.log(key);
}

Using values()

The values() method returns an iterator containing all values in insertion order:

for (const value of user.values()) {
  console.log(value);
}

Using entries()

The entries() method returns an iterator of key-value pairs. It is also the default iterator for a Map, so iterating directly over a Map produces the same pairs:

for (const [key, value] of user.entries()) {
  console.log(key, value);
}

// Equivalent:
for (const [key, value] of user) {
  console.log(key, value);
}

Using Objects as Map Keys

One important feature of Map is that keys are not limited to strings and symbols. You can use objects, arrays, and functions as keys. For object keys, Map compares object identity rather than the contents of the objects.

const userOne = { id: 1 };
const userTwo = { id: 1 };

const userRoles = new Map();

userRoles.set(userOne, "Admin");
userRoles.set(userTwo, "Editor");

console.log(userRoles.get(userOne)); // Admin
console.log(userRoles.get(userTwo)); // Editor
console.log(userRoles.size); // 2

Although userOne and userTwo contain the same properties, they are two different object references. Therefore, they are treated as separate keys.

To retrieve a value using an object key, you must have the original object reference:

const key = { code: "A1" };
const map = new Map();

map.set(key, "Available");

console.log(map.get(key)); // Available
console.log(map.get({ code: "A1" })); // undefined

Convert a Map to an Array

You can convert a Map into an array using the spread syntax or Array.from(). Both approaches produce an array of key-value pairs.

const map = new Map([
  ["name", "Rafi"],
  ["age", 28]
]);

const entriesArray = [...map];
console.log(entriesArray);
// [["name", "Rafi"], ["age", 28]]

const anotherArray = Array.from(map);
console.log(anotherArray);

To get only keys or values as arrays, combine Array.from() with the corresponding iterator:

const keys = Array.from(map.keys());
const values = Array.from(map.values());

console.log(keys);   // ["name", "age"]
console.log(values); // ["Rafi", 28]

Convert an Array to a Map

You can create a Map from an array of key-value pairs by passing the array to the Map constructor. Each inner array must contain exactly the key and value you want to store.

const entries = [
  ["HTML", "Markup language"],
  ["CSS", "Style sheet language"],
  ["JavaScript", "Programming language"]
];

const technologyMap = new Map(entries);

console.log(technologyMap.get("JavaScript"));
// Programming language

If an input array contains repeated keys, the last value for that key is retained in the resulting Map.

Practical Example: Count Items Using a Map

A Map is useful for counting how often each item appears in a list. The following example counts repeated product names:

const products = [
  "Laptop",
  "Mouse",
  "Keyboard",
  "Mouse",
  "Laptop",
  "Mouse"
];

const productCounts = new Map();

for (const product of products) {
  const currentCount = productCounts.get(product) ?? 0;
  productCounts.set(product, currentCount + 1);
}

console.log(productCounts);
// Map(3) {
//   "Laptop" => 2,
//   "Mouse" => 3,
//   "Keyboard" => 1
// }

The nullish coalescing operator (??) supplies zero when the product does not yet have a count. The loop then increments that count and stores it back in the Map. This pattern is useful for frequency analysis, shopping cart summaries, and simple analytics.

Map vs JavaScript Object

Both Map and plain objects can store values using keys, but they are designed for different situations. A plain object is often suitable for records with fixed property names. Map is usually a better choice when keys are dynamic or can be values other than strings and symbols.

Feature Map Object
Key types Any value Strings and symbols
Key order Insertion order Defined property-order rules
Number of entries Available through size Usually counted with Object.keys()
Iteration Directly iterable Not directly iterable by default
Clear all entries clear() method No built-in clear method
Prototype Map methods are provided by Map.prototype Ordinary objects may inherit properties

Choose Map when you need frequent additions and removals, non-string keys, or straightforward iteration over key-value pairs. Choose an object when representing a structured record or when working with JSON data, since JSON directly represents objects but does not serialize Map entries automatically.

Map and SameValueZero Key Comparison

Map determines whether two keys are the same using the SameValueZero comparison algorithm. For primitive values, this means values such as NaN are considered equal to themselves, and positive zero and negative zero are treated as the same key.

const values = new Map();

values.set(NaN, "Not a number");
values.set(NaN, "Updated value");

console.log(values.size); // 1
console.log(values.get(NaN)); // Updated value

values.set(+0, "Zero");
values.set(-0, "Negative zero");

console.log(values.size); // 2

Objects and functions are compared by reference identity. Two separate objects with identical properties remain different keys, as shown in the object-key example above.

Map Methods and Properties Reference

Method or property Description
new Map() Creates a new Map collection.
set(key, value) Adds an entry or updates an existing key.
get(key) Returns the value associated with a key.
has(key) Checks whether a key exists.
delete(key) Removes one entry by key.
clear() Removes all entries.
size Returns the number of entries.
keys() Returns an iterator of keys.
values() Returns an iterator of values.
entries() Returns an iterator of key-value pairs.
forEach(callback) Executes a callback for each entry.