Skip to content

Map

This lesson explains Map with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.

ES6+ Map Overview

Map is an ES6 collection that stores key-value pairs. Unlike plain objects, Map keys can be any type, including objects, functions, and symbols, and Map preserves insertion order.

Map is useful for caches, lookup tables, frequency counting, metadata storage, and any scenario where you need reliable key-value access with non-string keys.

Feature Description
Introduced In ES6 (ECMAScript 2015)
Stores Key-value pairs
Key Types Any value type
Main Methods set(), get(), has(), delete()
Size Property map.size
Common Uses Caches, lookups, counts, metadata, object keys

Basic Map Example

const users =
  new Map();

users.set("alex", "Admin");
users.set("sam", "Editor");
users.set("riya", "Viewer");

console.log(
  users.get("alex")
);
console.log(
  users.has("sam")
);
console.log(users.size);

users.delete("riya");

console.log(
  users.has("riya")
);

Use set() to add entries, get() to read values, and has() to check whether a key exists.

How Map Works

A Map stores entries as unique keys mapped to values. Keys are compared by reference or value depending on type, and the collection remembers the order in which entries were added.

Step Description Example
Create Map Start an empty or initial Map. new Map()
Add Entry Store a key-value pair. map.set(key, value)
Read Entry Retrieve a value by key. map.get(key)
Check Key See if a key exists. map.has(key)
Iterate Loop over keys, values, or entries. for...of

Map Methods Reference

Method / Property Purpose Returns
set(key, value) Add or update an entry. The Map object
get(key) Read a value by key. Value or undefined
has(key) Check if key exists. Boolean
delete(key) Remove an entry. Boolean
clear() Remove all entries. undefined
size Get number of entries. Number
keys(), values(), entries() Iterate over Map data. Iterator

Create a Map from an Array

const productPrices =
  new Map([
    ["keyboard", 79],
    ["mouse", 29],
    ["monitor", 249]
  ]);

console.log(
  productPrices.get("mouse")
);
console.log(productPrices.size);

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

You can initialize a Map with an array of [key, value] pairs, which is useful when converting existing data.

Using Objects as Map Keys

const userA = { id: 1 };
const userB = { id: 2 };

const sessions =
  new Map();

sessions.set(userA, "token-a");
sessions.set(userB, "token-b");

console.log(
  sessions.get(userA)
);
console.log(
  sessions.has(userB)
);

One major advantage of Map over plain objects is that object keys can be stored directly without converting them to strings.

Iterate Over a Map

const settings =
  new Map([
    ["theme", "dark"],
    ["language", "en"],
    ["notifications", true]
  ]);

settings.forEach(
  (value, key) => {
    console.log(`${key}: ${value}`);
  }
);

console.log([
  ...settings.keys()
]);

console.log([
  ...settings.values()
]);

Map supports forEach(), for...of, and iterator methods for keys, values, and entries.

Count Word Frequency with Map

const words = [
  "js",
  "map",
  "js",
  "set",
  "map",
  "js"
];

const frequency =
  new Map();

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

console.log(frequency);

Map is a clean choice for counting occurrences because get() and set() make updates easy to read.

Simple Cache Example

const cache =
  new Map();

function fetchUser(id) {
  if (cache.has(id)) {
    return cache.get(id);
  }

  const user = {
    id,
    name: `User ${id}`
  };

  cache.set(id, user);
  return user;
}

console.log(fetchUser(1));
console.log(fetchUser(1));

Maps are commonly used as in-memory caches because key lookup is fast and the API is straightforward.

Convert Between Object and Map

const user = {
  id: 10,
  name: "Alex",
  role: "admin"
};

const userMap =
  new Map(
    Object.entries(user)
  );

const backToObject =
  Object.fromEntries(userMap);

console.log(userMap);
console.log(backToObject);

You can convert plain objects to Maps with Object.entries() and convert back with Object.fromEntries().

Map vs Plain Object

Feature Map Plain Object
Key Types Any type Mostly strings and symbols
Size map.size Manual counting needed
Iteration Directly iterable Needs helper methods
Order Insertion order preserved Mostly preserved for string keys
Best For Dynamic key-value collections Fixed-shape records and JSON

Map Collection vs Array.map()

Do not confuse the Map collection with the Array.prototype.map() method. They solve different problems.

// Map collection
const roles =
  new Map([
    ["alex", "admin"],
    ["sam", "editor"]
  ]);

// Array.map() method
const numbers = [1, 2, 3];
const doubled =
  numbers.map((n) => n * 2);

console.log(roles.get("alex"));
console.log(doubled);

Common Map Use Cases

  • Lookup tables and dictionaries.
  • Frequency counting and grouping data.
  • Caching function results or API responses.
  • Storing metadata keyed by object references.
  • Mapping IDs to records in applications.
  • Tracking state in games, dashboards, or editors.
  • Building indexes from arrays efficiently.

Map Best Practices

  • Use Map when keys are dynamic or non-string values.
  • Prefer map.has(key) before assuming a value exists.
  • Use map.size instead of manually counting entries.
  • Iterate with for...of or forEach() for clarity.
  • Convert to objects only when JSON serialization is required.
  • Choose descriptive key types intentionally, especially object keys.
  • Clear or delete unused entries in long-lived caches.

Common Map Mistakes

  • Confusing Map with Array.map().
  • Expecting get() to throw when a key is missing.
  • Using plain objects when Map would handle dynamic keys better.
  • Assuming two similar-looking object keys are the same key.
  • Forgetting that get() returns undefined for missing keys.
  • Trying to JSON.stringify a Map directly without converting it.
  • Not clearing large Maps when they are no longer needed.

Key Takeaways

  • Map stores key-value pairs with keys of any type.
  • Use set(), get(), has(), and delete() to manage entries.
  • Map preserves insertion order and exposes size directly.
  • It is ideal for lookups, caches, counts, and dynamic collections.
  • It is different from the array map() method.

Pro Tip

Reach for Map when keys are not simple strings or when you need frequent add, delete, and size operations on a collection.