Chapter 13: JavaScript Map – Advanced Data Structures in ES6
ES6 introduced Map as a new data structure to store key-value pairs. While similar to objects, Maps come with added features like guaranteed insertion order and the ability to use objects, arrays, or functions as keys.
🧱 Creating a Map
const newMap = new Map();
console.log(newMap); // Map(0) {}
➕ Adding Items to a Map
let userMap = new Map();
userMap.set('data', { name: 'Umar', age: 32 });
console.log(userMap);
// Map(1) { 'data' => { name: 'Umar', age: 32 } }
// Using an object as a key
let obj = {};
userMap.set(obj, { role: 'admin' });
console.log(userMap);
🔍 Getting Map Values
console.log(userMap.get('data'));
// { name: 'Umar', age: 32 }
✅ Checking Key Existence
console.log(userMap.has('data')); // true
console.log(userMap.has('email')); // false
❌ Deleting Elements
userMap.delete('data'); // true
console.log(userMap); // Remaining entries
userMap.clear(); // Removes all entries
console.log(userMap); // Map(0) {}
📏 Map Size
console.log(userMap.size); // Number of key/value pairs
🔁 Looping Through Maps (for…of)
let userMap = new Map([
['name', 'Umar'],
['age', '32']
]);
for (let [key, value] of userMap) {
console.log(`${key} - ${value}`);
}
🔁 Looping Using forEach()
userMap.forEach((value, key) => {
console.log(`${key} - ${value}`);
});
🔑 Iterating Over Keys
for (let key of userMap.keys()) {
console.log(key);
}
🔓 Iterating Over Values
for (let value of userMap.values()) {
console.log(value);
}
🔁 Getting Both Keys and Values (entries())
for (let [key, value] of userMap.entries()) {
console.log(`${key}: ${value}`);
}
📊 Map vs Object Comparison
Feature | Map | Object |
---|---|---|
Key types | Can be any value (objects, functions, etc.) | Only strings and symbols |
Ordering | Maintains insertion order | No guaranteed order |
Size retrieval | Use map.size |
Use Object.keys().length |
Iteration | Directly iterable with for...of |
Must use Object.keys() or for...in |
Use case | Best for frequent additions/removals | Best for fixed structure data |
📘 Assignments: Practice JavaScript Maps
- Create a Map with 3 key-value pairs: name, age, and country. Print each entry.
- Use an object as a key in a Map and retrieve the value using
get()
. - Check if a certain key exists in a Map using
has()
. - Delete a specific key from the Map using
delete()
. Then, useclear()
. - Iterate through the Map keys, values, and entries. Log each with proper formatting.
📌 Summary
- Map stores key-value pairs with guaranteed order and flexibility.
- Use
set()
to add items,get()
to access, andhas()
to check existence. delete()
removes specific entries;clear()
wipes the entire map.- Loop using
for...of
,forEach()
, orentries()
. - Maps are more dynamic and powerful than plain objects for structured data.