Skip to main content

What is Map?

Map is a built-in data structure in JavaScript that stores "key -> value" pairs, like an object, but with a number of powerful advantages.

The main idea:

Map is like an object {}, but:

  • a key can be any data type (including objects and functions);
  • the order in which elements were added is preserved;
  • it is easy to know the number of entries (size);
  • you can iterate over values, keys, and pairs.

Creating a Map:

javascript
const map = new Map(); map.set("name", "Alice"); map.set("age", 25); map.set({ id: 1 }, "User Object"); console.log(map); // Map(3) { 'name' => 'Alice', 'age' => 25, { id: 1 } => 'User Object' }

Map methods

MethodDescriptionExample
set(key, value)add or update a pairmap.set("x", 10)
get(key)get a valuemap.get("x") // 10
has(key)check if a key existsmap.has("x") // true
delete(key)remove an elementmap.delete("x")
clear()clear the whole collectionmap.clear()
sizenumber of elementsmap.size // 3

Example of usage:

javascript
const userData = new Map(); userData.set("name", "Tim"); userData.set("role", "Admin"); console.log(userData.get("name")); // Tim console.log(userData.has("role")); // true console.log(userData.size); // 2

Keys can be anything!

javascript
const map = new Map(); const objKey = { id: 1 }; const funcKey = function () {}; const numKey = 123; map.set(objKey, "Object as key"); map.set(funcKey, "Function as key"); map.set(numKey, "Number as key"); console.log(map.get(objKey)); // "Object as key" console.log(map.get(funcKey)); // "Function as key"

In regular objects ({}) keys always get converted to strings. In Map they keep their type.

Iterating a Map

Map is an iterable structure, so you can use different loops.

for...of

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

forEach

javascript
map.forEach((value, key) => { console.log(`${key} -> ${value}`); });

Getting all keys, values, and pairs:

javascript
console.log([...map.keys()]); // ["name", "age"] console.log([...map.values()]); // ["Alice", 25] console.log([...map.entries()]); // [["name", "Alice"], ["age", 25]]

Comparison with an {} object

PropertyObjectMap
Key typeonly strings and symbolsany value
Key ordernot fully guaranteedinsertion order preserved
Size (length)must be counted manually.size property
Iterabilityneeds Object.keys() etc.iterated directly
Performanceworse with frequent insertions/deletionsfaster with many operations
Prototypehas one (Object.prototype)none - a "clean" collection

Practical usage example

Caching data:

javascript
const cache = new Map(); function getUser(id) { if (cache.has(id)) { return cache.get(id); // return from cache } const user = { id, name: "User" + id }; // suppose this is a request cache.set(id, user); return user; }

Linking data to objects:

javascript
const userRoles = new Map(); const alice = { name: "Alice" }; const bob = { name: "Bob" }; userRoles.set(alice, "admin"); userRoles.set(bob, "editor"); console.log(userRoles.get(alice)); // "admin"

Here Map lets you "attach" data to objects, which is impossible with regular {} objects.

Briefly:

PropertyDescription
Stores pairs"key -> value"
Key typeany
Orderpreserved
Can be iteratedYes
Key uniquenessYes
Methodsset, get, has, delete, clear
Size.size

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.