In this chapter, we will learn about JavaScript Maps. A Map is a collection of key-value pairs where keys can be of any type. We will cover:
- What is a Map?
- Creating Maps
- Adding and Removing Elements
- Accessing Map Elements
- Iterating Over Maps
- Map Methods
- Converting Maps to Arrays
- Simple Programs using Maps
What is a Map?
A Map is a collection of key-value pairs. Unlike objects, Maps allow keys to be of any type, including objects and primitive types. Maps maintain the order of elements based on the order of insertion.
Creating Maps
You can create a Map using the Map
constructor. You can also initialize a Map with an array of key-value pairs.
Syntax
let map = new Map(); let map = new Map(iterable);
Example
let map1 = new Map(); let map2 = new Map([ ["name", "Amit"], ["age", 25] ]); console.log(map1); // Map {} console.log(map2); // Map { 'name' => 'Amit', 'age' => 25 }
Adding and Removing Elements
You can add and remove elements from a Map using the set()
and delete()
methods.
Example
let map = new Map(); map.set("name", "Amit"); map.set("age", 25); console.log(map); // Map { 'name' => 'Amit', 'age' => 25 } map.delete("age"); console.log(map); // Map { 'name' => 'Amit' }
Accessing Map Elements
You can access elements in a Map using the get()
method and check for the existence of elements using the has()
method.
Example
let map = new Map([ ["name", "Amit"], ["age", 25] ]); console.log(map.get("name")); // Amit console.log(map.has("age")); // true console.log(map.has("gender")); // false
Iterating Over Maps
You can iterate over the elements of a Map using various methods such as for...of
, forEach()
, and others.
Example
let map = new Map([ ["name", "Amit"], ["age", 25] ]); // Using for...of for (let [key, value] of map) { console.log(`${key}: ${value}`); } // Using forEach map.forEach((value, key) => { console.log(`${key}: ${value}`); });
Output:
name: Amit age: 25 name: Amit age: 25
Map Methods
Maps provide several useful methods for working with their elements.
set()
Adds or updates an element in the Map.
let map = new Map(); map.set("name", "Amit"); map.set("age", 25); console.log(map); // Map { 'name' => 'Amit', 'age' => 25 }
get()
Retrieves the value associated with a key.
console.log(map.get("name")); // Amit
has()
Checks if a key exists in the Map.
console.log(map.has("age")); // true
delete()
Removes an element from the Map.
map.delete("age"); console.log(map); // Map { 'name' => 'Amit' }
clear()
Removes all elements from the Map.
map.clear(); console.log(map); // Map {}
size
Returns the number of elements in the Map.
let map = new Map([ ["name", "Amit"], ["age", 25] ]); console.log(map.size); // 2
Converting Maps to Arrays
You can convert a Map to an array using the spread operator or the Array.from()
method.
Example
let map = new Map([ ["name", "Amit"], ["age", 25] ]); let array1 = [...map]; let array2 = Array.from(map); console.log(array1); // [ [ 'name', 'Amit' ], [ 'age', 25 ] ] console.log(array2); // [ [ 'name', 'Amit' ], [ 'age', 25 ] ]
Simple Programs using Maps
Program 1: Counting Word Frequency
function countWordFrequency(text) { let words = text.split(" "); let wordCount = new Map(); words.forEach(word => { let count = wordCount.get(word) || 0; wordCount.set(word, count + 1); }); return wordCount; } let text = "hello world hello everyone"; let wordFrequency = countWordFrequency(text); wordFrequency.forEach((count, word) => { console.log(`${word}: ${count}`); });
Output:
hello: 2 world: 1 everyone: 1
Program 2: Storing User Data
let users = new Map(); users.set(1, { name: "Amit", age: 25 }); users.set(2, { name: "Neha", age: 30 }); users.forEach((user, id) => { console.log(`ID: ${id}, Name: ${user.name}, Age: ${user.age}`); });
Output:
ID: 1, Name: Amit, Age: 25 ID: 2, Name: Neha, Age: 30
Conclusion
In this chapter, you learned about JavaScript Maps, including how to create Maps, add and remove elements, access Map elements, iterate over Maps, use Map methods, and convert Maps to arrays. We also provided various use cases with simple programs to demonstrate the usage of Maps. Understanding how to effectively use Maps is essential for managing collections of key-value pairs in JavaScript.