AI Reading
Quick summary of this article
JavaScript Maps, introduced in ES6, offer a flexible way to store key-value pairs. Unlike regular objects, Maps maintain insertion order and allow any data type—including objects, arrays, and functions—to be used as keys. They provide dedicated methods for adding, retrieving, checking, and deleting entries, and can be easily iterated with loops. Maps are particularly useful for dynamic data where keys and values change frequently.
- Flexible keys: Maps accept any value as a key (objects, functions, arrays), while objects only allow strings and symbols.
- Core methods: Use
set()to add items,get()to retrieve values,has()to check key existence, anddelete()orclear()to remove entries. - Iteration: Maps are directly iterable with
for...of,forEach(), or by usingkeys(),values(), andentries()methods. - Size property: Use
map.sizeto quickly get the number of entries, instead of counting keys manually like with objects. - Best use case: Maps are ideal for frequent additions and removals of data, whereas objects are better for fixed, simple structures.
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.
