JavaScript Maps — Interview Questions & Answers
Ques: What is a Map in JavaScript?
Ans: A Map is a collection of key-value pairs, similar to objects — but with improved capabilities.
Unlike objects, keys in Maps can be of any type (not just strings or symbols).
const map = new Map();
map.set('name', 'John');
map.set(100, 'score');
map.set(true, 'isActive');
Ques: Why use Map instead of Object?
| Feature | Object | Map |
|---|---|---|
| Key types | String / Symbol | Any data type |
| Order | Unordered | Maintains insertion order |
| Iteration | Complex (Object.keys, etc.) | Easy (forEach, for..of) |
| Size | Manual count | .size property |
| Performance | Slower for frequent insert/delete | Optimized for key-value operations |
Ques: How do you create a Map?
Ans: Using the new Map() constructor:
const user = new Map([
['name', 'Alice'],
['age', 25]
]);
Ques: How do you add or update values in a Map?
Ans: Use the .set() method:
const map = new Map();
map.set('color', 'blue');
map.set('color', 'red'); // updates existing key
Ques: How do you retrieve a value from a Map?
Ans: Use .get(key):
console.log(map.get('color')); // red
Ques: How do you check if a key exists in a Map?
Ans: Use .has(key):
console.log(map.has('color')); // true
Ques: How do you remove a key-value pair?
Ans: Use .delete(key) or .clear() to empty all entries:
map.delete('color');
map.clear();
Ques: How do you find the number of entries in a Map?
Ans: Use the .size property:
console.log(map.size);
Ques: How do you iterate through a Map?
for (let [key, value] of map) {
console.log(`${key}: ${value}`);
}
Or use .forEach():
map.forEach((value, key) => console.log(key, value));
Ques: How do you convert a Map to an Array?
const arr = Array.from(map);
console.log(arr); // [[key, value], [key, value]]
Ques: How do you convert an Object to a Map?
const obj = { name: 'John', age: 30 };
const map = new Map(Object.entries(obj));
Ques: How do you convert a Map back to an Object?
const obj = Object.fromEntries(map);
Ques: What are the main Map methods?
| Method | Description |
|---|---|
.set(key, value) | Adds/updates a key-value pair |
.get(key) | Returns value for the key |
.has(key) | Checks key existence |
.delete(key) | Removes a key |
.clear() | Clears all entries |
.size | Returns total number of entries |
.keys() | Returns all keys |
.values() | Returns all values |
.entries() | Returns all key-value pairs |
Ques: Example: Iterating keys and values separately
const fruits = new Map([
['apple', 10],
['banana', 20],
]);
for (let key of fruits.keys()) console.log(key);
for (let value of fruits.values()) console.log(value);
Ques: Are Maps ordered?
Ans: Yes, Maps maintain insertion order, unlike regular objects.
Ques: Can Map keys be objects?
Ans: Yes, any object or even a function can be a key.
const objKey = { id: 1 };
const map = new Map();
map.set(objKey, 'User Data');
console.log(map.get(objKey)); // User Data
Ques: What happens if you use the same key twice in a Map?
Ans: It overwrites the previous value — keys are unique.
Ques: Difference between Map and WeakMap
| Feature | Map | WeakMap |
|---|---|---|
| Key Types | Any type | Only objects |
| Garbage Collection | No | Yes |
| Iteration | Iterable | Not iterable |
| Size Property | Yes | No |
| Use Case | Data storage | Temporary references |
Ques: What is a WeakMap?
Ans: A WeakMap stores key-value pairs where keys must be objects and are weakly referenced (garbage-collected if no other references exist).
let obj = { id: 1 };
const wm = new WeakMap();
wm.set(obj, "Secret Info");
obj = null; // key-value pair can be garbage collected
Ques: Can you loop through a WeakMap?
Ans: No, WeakMap is not iterable because its keys are weakly held and can disappear anytime.
Ques: Use cases of Map
- Caching data results (like API responses)
- Storing metadata for DOM elements
- Counting frequency of items
- Maintaining insertion order of dynamic data
Ques: Use cases of WeakMap
- Private data storage for class instances
- Avoiding memory leaks with temporary object references
Ques: Example: Counting word frequency using Map
const text = "apple banana apple orange banana apple";
const words = text.split(" ");
const count = new Map();
words.forEach(word => {
count.set(word, (count.get(word) || 0) + 1);
});
console.log(count);
// Map { 'apple' => 3, 'banana' => 2, 'orange' => 1 }
