JavaScript Map

Beginner
8 min read
Updated: Nov 2026
3 examples
Key / value

Definition and Usage

In JavaScript, a Map stores key / value pairs. Keys can be any type — strings, numbers, objects, NaN, and more. Entries keep insertion order. You can read how many there are with map.size, and you can loop with for...of or forEach().

You create one with new Map(), then use set(), get(), has(), and delete(). Unlike a plain object, a Map does not treat string keys as property names, and it does not inherit from Object.prototype.

This page teaches the ideas; the Map Methods index lists every method guide (set(), get(), Map.groupBy(), and more).

Any key, reliable size, easy to loop.

A Map is the built-in collection when you need key/value data that you can count and iterate in a stable order.

JavaScript Syntax

Common ways to create a Map and use it:

JavaScript
const map = new Map();                    // empty
map.set("id", 1);                          // store (returns map)
map.get("id");                             // 1
map.has("id");                             // true
map.delete("id");                          // true
map.size;                                  // 0

const filled = new Map([["a", 1], ["b", 2]]);
for (const [k, v] of filled) {
  // insertion order: "a" then "b"
}

Keys and SameValueZero

Map keys can be anything: strings, numbers, objects, arrays, functions, NaN, null, and undefined. Keys are compared with SameValueZero: NaN equals NaN, and +0 and -0 count as the same key. Object keys match by identity — two different objects with the same shape are two different keys.

That is different from a plain object, where every key becomes a string (or symbol), and different from a WeakMap, which only allows object (and local symbol) keys and cannot be listed.

When to Use a Map

UseHow it worksWhy Map fits
Non-string keysKey by an object, a number, or NaNObjects coerce keys to strings; Map does not
Frequent add / removeUpdate a lookup table as data arrivessize, delete(), and clear() are built in
Preserve orderWalk entries in the order you inserted themInsertion order is guaranteed
Avoid prototype surprisesDo not inherit toString or other Object keysA Map is not an object bag of properties

Map vs WeakMap

QuestionMapWeakMap
Allowed keysAny valueObjects (and local symbols) only
Keeps keys alive?Yes, until you delete themNo, keys can be cleaned up
Sizemap.sizeNone
Loop over entriesfor...of, forEach(), keys()Not possible
Empty itclear()Create a new WeakMap
Best forData you want to list, count, or showHidden extra data about objects

Newer Upsert Methods

getOrInsert() and getOrInsertComputed() read a value, and store one first if the key is missing. They were added to Map and WeakMap together and replace the long if (!map.has(k)) map.set(k, v) pattern.

They are not in every engine yet. We tested Node.js 24.15, which does not have them, and Chrome 148, which does. Check before you rely on them: typeof Map.prototype.getOrInsert === "function". Their examples include a tiny fallback so they still run everywhere.

JavaScript Examples

Three short programs that show how a Map works.

Example 1 — Store, Read, Check, and Remove

Create a Map and walk through set, get, has, delete, and size.

JavaScript
const map = new Map();

map.set("score", 10);
console.log(map.get("score"));    // 10
console.log(map.has("score"));    // true
console.log(map.size);            // 1
console.log(map.delete("score")); // true
console.log(map.size);            // 0
set() tutorial

How It Works

  1. Put a value in. map.set("score", 10) stores 10 under the key "score", and get() reads it back.
  2. Ask and count. has("score") is true, and size is 1 while that entry exists.
  3. Remove and count again. delete("score") returns true, and size drops to 0.

Example 2 — Strings, Objects, and NaN as Keys

Map keys can be any value. Object keys use identity, and NaN matches itself.

JavaScript
const map = new Map();
const user = { id: 1 };

map.set("name", "Ada");
map.set(user, "admin");
map.set(NaN, "oops");

console.log(map.get("name"));                 // Ada
console.log(map.get(user));                   // admin
console.log(map.get({ id: 1 }) === undefined); // true
console.log(map.get(NaN));                    // oops
get() tutorial

How It Works

  1. Strings work as usual. set("name", "Ada") and get("name") behave like a simple lookup.
  2. Objects need the same reference. user works as a key, but a new { id: 1 } is a different object, so get() finds nothing.
  3. NaN matches NaN. Even though NaN !== NaN in normal code, Map treats NaN as the same key.

Example 3 — Iterate with for...of

A Map remembers insertion order. Loop with for...of over each [key, value] pair.

JavaScript
const map = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3]
]);

for (const [key, value] of map) {
  console.log(key + "=" + value);
}

console.log(map.size); // 3
Map methods index

How It Works

  1. Start with pairs. The constructor fills the Map from a list of [key, value] pairs in order.
  2. Unpack each entry. for...of yields [key, value], so you can print both in one loop.
  3. Size stays visible. Unlike WeakMap, map.size tells you how many entries are in the Map.

Map Method Groups

Map has twelve method guides in this track. Each one has a full tutorial with examples you can run in the browser.

MethodUse it to
set()Store a value for a key (chainable)
get()Read the value, or undefined if the key is missing
has()Ask whether a key is in the Map
delete()Remove one entry
clear()Remove every entry
keys()Iterate keys in insertion order
values()Iterate values in insertion order
entries()Iterate [key, value] pairs
forEach()Call a function for each entry
getOrInsert()Read the value, or store a default first (newer)
getOrInsertComputed()Same, but build the default only when needed (newer)
Map.groupBy()Static helper: group a list into a Map (ES2024)

Full list with the constructor: Map Methods index.

Frequently Asked Questions

A Map is a collection of key and value pairs. Keys can be any type: strings, numbers, objects, functions, and even NaN. You create one with new Map(), add pairs with set(), read with get(), and check size with the size property.
Object keys are mostly strings or symbols. Map keys can be any value, including objects. Map also keeps insertion order, has a size property, and is built for frequent add and remove. Prefer Map when keys are not plain string names.
Map accepts any key, keeps keys alive, has size, and can be looped over. WeakMap accepts only objects as keys, does not keep them alive, and cannot be counted or iterated. Choose Map when you need to list or count entries.
Use for...of on the Map itself to get each [key, value] pair. You can also use map.keys(), map.values(), map.entries(), or map.forEach(). Entries follow insertion order.
The main ones are set, get, has, delete, and clear. You also get size, keys, values, entries, and forEach. Newer helpers like getOrInsert appear on some engines. Start with set, get, has, and size.

Browse every Map method

Open the index for set(), get(), has(), delete(), clear(), iterators, upserts, and Map.groupBy().

Map Methods index →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

16 people found this page helpful