What is a JavaScript Map?
A Map is a data structure that stores key-value pairs. Unlike objects, Maps allow keys to be any data type (objects, functions, primitives) and preserve insertion order.
How do you create a new, empty JavaScript Map?
const myMap = new Map();
How do you initialize a Map with initial key-value pairs when creating it?
const myArray = [[“name”, “John”], [“age”, 30]];
const myMap = new Map(myArray);
How do you add a new key-value pair to a Map or update an existing value?
myMap.set(“city”, “New York”);
myMap.set(“age”, 31); // updates existing key
How do you retrieve a value from a Map using its key?
const cityName = myMap.get(“city”); // ‘New York’
If key doesn’t exist, .get() returns undefined.
How do you check if a Map contains a key?
myMap.has(“name”); // true
myMap.has(“address”); // false
How do you remove a key-value pair from a Map?
myMap.delete(“city”); // true if removed, false otherwise
How do you remove all key-value pairs from a Map?
myMap.clear(); // removes all entries
How do you iterate through all key-value pairs in a Map?
for (const [key, value] of myMap) {
console.log(key, value);
}
How do you iterate through all the keys in a Map?
for (const key of myMap.keys()) {
console.log(key);
}
How do you iterate through all the values in a Map?
for (const value of myMap.values()) {
console.log(value);
}
What is the significance of using objects as keys in a Map?
Maps allow associating data directly with objects — useful for caching or metadata storage.
How do you get the number of key-value pairs in a Map?
const mapSize = myMap.size; // returns number of entries
What are the key differences between Object and Map?
When might you choose Map over Object?
When you need:
- Non-string keys (objects/functions)
- Ordered entries
- Frequent add/remove operations
- Quick access to collection size (.size property)