Lesson 82 – JavaScript Maps
In this lesson, we will explore Maps in JavaScript—what they are, how to create and manipulate them, and when to use them over regular objects.
What is a Map?
A Map is a collection of key-value pairs, just like an object. However, Maps offer some advantages over objects:
- Keys can be any type (not just strings or symbols).
- Maps maintain the insertion order of elements.
- Maps have a size property.
- Maps provide built-in methods for iteration, addition, deletion, etc.
Creating a Map
const myMap = new Map();
Or initialize with key-value pairs:
const capitals = new Map([
["Ghana", "Accra"],
["France", "Paris"],
["Japan", "Tokyo"]
]);
Basic Map Methods
set(key, value)
Adds a new key-value pair.
capitals.set("Germany", "Berlin");
get(key)
Retrieves the value for a given key.
console.log(capitals.get("France")); // Paris
has(key)
Checks if a key exists.
console.log(capitals.has("Japan")); // true
delete(key)
Deletes a key-value pair.
capitals.delete("Ghana");
clear()
Removes all key-value pairs.
capitals.clear();
size
Returns the number of key-value pairs.
console.log(capitals.size);
Iterating through Maps
for (let [country, city] of capitals) {
console.log(`${country} ? ${city}`);
}
You can also use:
map.keys()
– iterate over keysmap.values()
– iterate over valuesmap.entries()
– iterate over key-value pairs
When to Use Maps?
Use Maps when:
- You need key-value pairs with non-string keys.
- You need to maintain insertion order.
- You need frequent additions and deletions.
Try Your Hand
- Create a Map of usernames to email addresses.
- Add a new entry to it.
- Check if a specific username exists.
- Loop through the Map and log each entry.
Summary
- Maps are great for flexible and efficient key-value storage.
- They work well when the keys are not just strings.
- Useful methods:
set
,get
,has
,delete
,clear
,size
, and iteration helpers.