Topic 10: JavaScript Map Object
📖 12 min read · 🎯 advanced · 🧭 Prerequisites: javascript-object, using-other-open-source-material
Why this matters
Up until now, you've probably been storing related data in plain JavaScript objects — and honestly, that works fine for a while. But here's the thing — plain objects have quiet limitations that only show up when things get messy: keys must be strings, order isn't guaranteed, and there's no clean way to count entries. The Map object fixes all of that. It's a purpose-built key-value container where keys can be anything — numbers, objects, even functions — and the order you insert data is the order you get it back. Once you see what Map can do, you'll know exactly when to reach for it.
What You'll Learn
- What a
Mapis and how it differs from a plain JavaScript object - How to create a
Mapand add, retrieve, check, remove, and clear entries usingset,get,has,delete, andclear - How to iterate over a
Mapusingfor…ofloops (entries, keys, values) and theforEachmethod - How to use a
Mapin a realistic scenario: storing and managing structured user records
The Analogy
Think of a Map as a coat-check room at an upscale Vizag theatre. Each patron hands over their coat and receives a numbered ticket — that ticket is the key, the coat is the value. The attendant hands back the exact coat when you present the exact ticket (get), can confirm whether ticket number 42 was issued (has), can remove a specific coat and retire its ticket (delete), and can sweep the entire room clean at closing time (clear). Unlike the chaotic lost-and-found box next door — the plain JavaScript object — the coat-check room remembers the exact order in which coats were deposited, and the ticket can be anything: a number, a string, even another object.
Chapter 1: What Is a Map?
A Map is a built-in JavaScript collection that stores key-value pairs where both keys and values can be of any type — strings, numbers, objects, functions, even other Maps.
Two properties set it apart from plain objects:
- Insertion order is preserved. When you iterate a
Map, entries come back in the order they were added. Plain objects do not guarantee this for all key types. - Any value can be a key. Plain objects coerce keys to strings. A
Mapkeeps keys as-is, so the number1and the string"1"are two distinct keys.
Key Map properties and methods at a glance:
| Member | Type | Purpose |
|---|---|---|
map.size | property | Number of key-value pairs currently stored |
map.set(key, value) | method | Add or update an entry |
map.get(key) | method | Retrieve the value for a key |
map.has(key) | method | Returns true if the key exists |
map.delete(key) | method | Remove a single entry |
map.clear() | method | Remove all entries |
map.keys() | method | Iterator over keys |
map.values() | method | Iterator over values |
map.entries() | method | Iterator over [key, value] pairs |
map.forEach(cb) | method | Execute a callback for each entry |
Chapter 2: Creating and Using a Map
Creating a Map
Use the Map constructor — no arguments needed for an empty map:
let map = new Map();
Adding Elements — set
map.set('name', 'Alice');
map.set('age', 25);
map.set('city', 'Vizag');
set returns the Map itself, so calls can be chained:
map.set('name', 'Alice').set('age', 25).set('city', 'Vizag');
Accessing Elements — get
console.log(map.get('name')); // Output: Alice
console.log(map.get('age')); // Output: 25
If the key does not exist, get returns undefined.
Checking for Keys — has
console.log(map.has('city')); // Output: true
console.log(map.has('country')); // Output: false
Removing a Single Entry — delete
map.delete('age');
console.log(map.has('age')); // Output: false
delete returns true if the key existed and was removed, false otherwise.
Clearing All Entries — clear
map.clear();
console.log(map.size); // Output: 0
Chapter 3: Iterating Over a Map
One of the most useful traits of Map is how naturally it supports iteration. Because insertion order is guaranteed, loops are predictable.
Using the for…of Loop
You can iterate over entries, keys, or values separately:
let map = new Map([
['name', 'Alice'],
['age', 25],
['city', 'Vizag']
]);
// Iterating over entries (destructured as [key, value])
for (let [key, value] of map) {
console.log(key + ': ' + value);
}
// Output:
// name: Alice
// age: 25
// city: Vizag
// Iterating over keys only
for (let key of map.keys()) {
console.log(key);
}
// Output: name age city
// Iterating over values only
for (let value of map.values()) {
console.log(value);
}
// Output: Alice 25 Vizag
Note: passing an array of [key, value] pairs directly to the Map constructor is a convenient shorthand for creating a pre-populated map.
Using the forEach Method
forEach receives the callback in (value, key) order — the opposite of what you might expect from for…of destructuring, so pay attention:
map.forEach((value, key) => {
console.log(key + ': ' + value);
});
// Output:
// name: Alice
// age: 25
// city: Vizag
flowchart LR
A[new Map] -->|set| B[(Map Store)]
B -->|get| C[Value]
B -->|has| D[true / false]
B -->|delete| E[Entry removed]
B -->|clear| F[Empty Map]
B -->|for…of / forEach| G[Iteration]
Chapter 4: Practical Example — Storing User Information
the trainer challenged the class to put everything together: a Map keyed by numeric user IDs, each value being a structured user object.
// Creating a new Map
let users = new Map();
// Adding users to the Map
users.set(1, { name: 'Alice', age: 25, city: 'Vizag' });
users.set(2, { name: 'Bob', age: 30, city: 'CoderTown' });
users.set(3, { name: 'Charlie', age: 35, city: 'DevCity' });
// Retrieving user information
console.log(users.get(1));
// Output: { name: 'Alice', age: 25, city: 'Vizag' }
console.log(users.get(2).name);
// Output: Bob
// Iterating over all users
users.forEach((user, id) => {
console.log(`ID: ${id}, Name: ${user.name}, Age: ${user.age}, City: ${user.city}`);
});
// Output:
// ID: 1, Name: Alice, Age: 25, City: Vizag
// ID: 2, Name: Bob, Age: 30, City: CoderTown
// ID: 3, Name: Charlie, Age: 35, City: DevCity
// Checking if a user exists
console.log(users.has(3)); // Output: true
// Deleting a user
users.delete(2);
console.log(users.has(2)); // Output: false
// Clearing all users
users.clear();
console.log(users.size); // Output: 0
Key observations from this example:
- The keys are numbers (
1,2,3) — not strings. A plain object would silently coerce them to"1","2","3". users.get(2).namechains directly off the retrieved object — no intermediate variable needed.- After
users.delete(2), the remaining entries (1and3) still iterate in original insertion order. users.sizereflects live state: afterclear()it is exactly0.
🧪 Try It Yourself
Task: Build a word-frequency counter using a Map.
Write a script that takes an array of words and counts how many times each word appears, then prints every word alongside its count.
Starter snippet:
const words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const freq = new Map();
for (const word of words) {
// If the word is already in the map, increment its count.
// If not, set it to 1.
freq.set(word, (freq.get(word) || 0) + 1);
}
freq.forEach((count, word) => {
console.log(`${word}: ${count}`);
});
Success criterion: Your console should print:
apple: 3
banana: 2
cherry: 1
Extend it: try adding more words, checking .has() before incrementing, or sorting entries by frequency before printing.
🔍 Checkpoint Quiz
Q1. How does a JavaScript Map differ from a plain JavaScript object when it comes to key types?
A) A Map only allows string keys, just like an object
B) A Map allows keys of any type; plain objects coerce all keys to strings
C) A Map only allows numeric keys
D) Plain objects allow any key type; Maps only allow strings
Q2. What does the following snippet print to the console?
let m = new Map();
m.set('x', 10);
m.set('y', 20);
m.delete('x');
console.log(m.size);
console.log(m.has('x'));
A) 2 then true
B) 1 then false
C) 0 then false
D) 2 then false
Q3. Given this code, what is logged and in what order?
let m = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of m) {
console.log(key);
}
A) 1, 2, 3
B) a, b, c (in insertion order, guaranteed)
C) a, b, c (but order is not guaranteed)
D) ['a',1], ['b',2], ['c',3]
Q4. You are building a session store for an HTTP server. Each active session is identified by a unique session object (not a string ID). Which data structure is more appropriate — a plain object or a Map — and why?
A1. B — A Map preserves the actual type of every key. Plain objects call .toString() on keys, so obj[1] and obj["1"] refer to the same slot, while map.get(1) and map.get("1") are entirely separate entries.
A2. B — After delete('x'), one entry remains ('y': 20), so m.size is 1. m.has('x') returns false because the key was removed.
A3. B — Map guarantees iteration in insertion order for all key types, so a, b, c are logged in that exact sequence. The for…of loop on a Map yields [key, value] pairs; destructuring [key, value] and logging key gives the string keys.
A4. A Map is the right choice. Plain objects can only use strings (or Symbols) as keys, so using a session object as a key would coerce it to "[object Object]" — making every session collide on the same slot. A Map keeps the object reference itself as the key, giving each session a unique, exact lookup.
🪞 Recap
- A
Mapstores key-value pairs where both keys and values can be of any type, unlike plain objects which coerce keys to strings. Mappreserves insertion order, making iteration predictable withfor…oforforEach.- Core methods —
set,get,has,delete,clear— cover the full lifecycle of entries;sizereports the live count. - You can iterate over entries, keys, or values independently using
map.entries(),map.keys(), andmap.values(). Mapshines for scenarios where keys are non-strings (numbers, objects) or where iteration order matters — such as user registries, frequency counters, and session stores.
📚 Further Reading
- MDN Web Docs — Map — the authoritative reference for every
Mapmethod, edge case, and browser compatibility note - JavaScript.info — Map and Set — a clear, example-driven walkthrough comparing
Mapto plain objects andWeakMap - Exploring ES6 by Dr. Axel Rauschmayer — deep-dive chapter on
Map,Set, and their weak counterparts - ⬅️ Previous: JavaScript Object
- ➡️ Next: Registration Form