JavaScript provides Map and Set objects to store collections of data. Maps store key-value pairs, while Sets store unique values. Both are useful for managing dynamic data efficiently.
This blog explains Maps and Sets with practical examples.
⭐ 1. JavaScript Map
A Map is a collection of key-value pairs where keys can be of any type.
let map = new Map();
map.set("name", "Sagar");
map.set("age", 22);
console.log(map.get("name")); // Sagar
console.log(map.size); // 2
Iterating Over Map
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
// Output:
// name: Sagar
// age: 22
Map Methods
map.has("age"); // true
map.delete("age"); // removes age
map.clear(); // removes all entries
⭐ 2. JavaScript Set
A Set is a collection of unique values (duplicates are ignored).
let set = new Set();
set.add(1);
set.add(2);
set.add(2); // duplicate ignored
console.log(set); // Set {1, 2}
Iterating Over Set
for (let value of set) {
console.log(value);
}
// Output:
// 1
// 2
Set Methods
set.has(1); // true
set.delete(1); // removes 1
set.clear(); // clears the set
⭐ 3. Why Use Maps & Sets
- Map: Store key-value pairs with keys of any type
- Set: Store unique values, automatically removing duplicates
- Efficient methods for lookup, insertion, and deletion
- Useful for collections, caching, and managing dynamic data
⭐ Conclusion
Maps and Sets are powerful ES6 data structures in JavaScript. Maps are ideal for key-value pairs, while Sets ensure uniqueness of elements. Using them properly improves performance and code clarity in complex applications.
📌 Citations
🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/
🔗 External Javascript Documentation:
https://www.w3schools.com/js/