JavaScript Maps
Key-value pairs with any data type as keys
πΊοΈ What are JavaScript Maps?
A Map is a collection of key-value pairs where keys can be any data type. Unlike objects, Maps maintain insertion order and provide better performance for frequent additions and removals.
// Creating a new Map
const myMap = new Map();
myMap.set('name', 'John');
myMap.set(1, 'number key');
myMap.set(true, 'boolean key');
console.log(myMap.get('name')); // 'John'
Output:
'John'
Key Map Features
Any Key Type
Keys can be any data type
map.set('string', 'value');
map.set(42, 'number key');
map.set(true, 'boolean key');
Size Property
Get number of key-value pairs
map.size; // 3
Insertion Order
Maintains order of insertion
for (let [key, value] of map) {
console.log(key, value);
}
Performance
Optimized for frequent updates
map.has(key); // Fast lookup
map.delete(key); // Fast removal
πΉ Creating Maps
Different ways to create and initialize Maps:
// Empty Map
const emptyMap = new Map();
// Map from array of arrays
const arrayMap = new Map([
['name', 'Alice'],
['age', 30],
['city', 'New York']
]);
// Map from another Map
const copyMap = new Map(arrayMap);
// Adding values after creation
const userMap = new Map();
userMap.set('id', 123);
userMap.set('username', 'john_doe');
userMap.set('active', true);
console.log(arrayMap.get('name')); // 'Alice'
console.log(userMap.size); // 3
Output:
'Alice'
3
3
πΉ Map vs Object
Understanding the differences between Maps and Objects:
Map Advantages:
- Any key type: Objects, functions, primitives
- Size property: Easy to get number of entries
- Iteration: Directly iterable
- Performance: Better for frequent additions/deletions
Object Advantages:
- JSON support: Can be serialized to JSON
- Syntax: Literal syntax available
- Property access: Dot notation and brackets
// Map with different key types
const map = new Map();
map.set('string', 'String key');
map.set(42, 'Number key');
map.set(true, 'Boolean key');
map.set({id: 1}, 'Object key');
// Object (keys are always strings)
const obj = {};
obj['string'] = 'String key';
obj[42] = 'Number key (converted to string)';
obj[true] = 'Boolean key (converted to string)';
console.log(map.size); // 4
console.log(Object.keys(obj).length); // 3
Output:
4
3
3
πΉ Basic Map Operations
Essential operations for working with Maps:
const inventory = new Map();
// Setting values
inventory.set('apples', 50);
inventory.set('bananas', 30);
inventory.set('oranges', 25);
// Getting values
console.log(inventory.get('apples')); // 50
console.log(inventory.get('grapes')); // undefined
// Checking if key exists
console.log(inventory.has('bananas')); // true
console.log(inventory.has('grapes')); // false
// Getting size
console.log(inventory.size); // 3
// Deleting entries
inventory.delete('oranges');
console.log(inventory.has('oranges')); // false
// Clearing all entries
inventory.clear();
console.log(inventory.size); // 0
Output:
50
undefined
true
false
3
false
0
undefined
true
false
3
false
0
πΉ Practical Map Examples
Real-world use cases for Maps:
πΈ User Cache System
const userCache = new Map();
// Store user data with ID as key
userCache.set(101, {name: 'Alice', role: 'admin'});
userCache.set(102, {name: 'Bob', role: 'user'});
userCache.set(103, {name: 'Charlie', role: 'moderator'});
// Quick user lookup
function getUser(id) {
return userCache.get(id) || {name: 'Unknown', role: 'guest'};
}
console.log(getUser(101)); // {name: 'Alice', role: 'admin'}
console.log(getUser(999)); // {name: 'Unknown', role: 'guest'}
Output:
{name: 'Alice', role: 'admin'}
{name: 'Unknown', role: 'guest'}
{name: 'Unknown', role: 'guest'}
πΈ Frequency Counter
function countFrequency(arr) {
const frequency = new Map();
for (const item of arr) {
frequency.set(item, (frequency.get(item) || 0) + 1);
}
return frequency;
}
const words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const wordCount = countFrequency(words);
console.log(wordCount); // Map {'apple' => 3, 'banana' => 2, 'cherry' => 1}
Output:
Map {'apple' => 3, 'banana' => 2, 'cherry' => 1}