JavaScript Map Interview Questions and Answers
Explore Map key-value collections, iteration, and how they differ from plain objects.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
- Convert a Map into an array of key-value pairs.
- Convert an object's own entries into a Map.
- How does Map behave when using an Array as a key?
- How to iterate a Map using forEach and for...of?
- What problem does a `Map` solve?
- How can a `Map` count occurrences in a list?
- Why are two object literals distinct keys in a `Map`?
Theoretical JavaScript Interview Questions
map transforms each element and returns a new array of the same length. filter tests each element and returns a new array with only the elements that pass. reduce walks through the array accumulating a single output value - a sum, an object, a string, whatever you need. In real code you'll use map and filter constantly; reduce is powerful but can be hard to read, so only reach for it when a simpler approach won't do.
A Map is a key-value store where keys can be any type - objects, functions, primitives, anything. That's the big difference from plain objects where keys are always strings or Symbols. Maps also maintain insertion order and have a .size property. Use a Map when your keys aren't strings, when you need to frequently add/remove entries, or when key-value pairs are the primary purpose of the data structure.
WeakMap is like Map but keys must be objects and are held weakly - when the key object gets garbage collected, the entry disappears automatically. This makes it great for associating private data with objects without causing memory leaks. A classic pattern is using a WeakMap to store private state for class instances: the data is automatically cleaned up when the instance is gone.
Since Map's set() method returns the Map itself, you can chain multiple set() calls: new Map().set('a', 1).set('b', 2).set('c', 3). It's a builder pattern for initializing a Map inline. That said, for larger Maps it's usually cleaner to just pass an array of pairs to the constructor: new Map([['a', 1], ['b', 2]]).
Map uses the SameValueZero algorithm for key equality, which means objects (including arrays) are compared by reference, not value. So map.set([1,2], 'x') and then map.get([1,2]) returns undefined because that's a different array instance. You'd need to hold a reference to the original array to retrieve the value. This trips people up constantly - if you need value-based lookup, stringify the key or rethink your data structure.
With forEach, the callback receives value first, then key - the reverse of what you might expect coming from plain objects: map.forEach((value, key) => {}). With for...of, destructure the entries: for (const [key, value] of map) {}. Both respect insertion order. The for...of approach is usually nicer since it supports break and works naturally with async/await.
A `Map` stores key-value pairs and permits keys of any value type, including objects. It also exposes collection-oriented operations such as `size`, `set`, `get`, and `delete`.
Object keys are compared by identity using `SameValueZero`, not by comparing their properties. Two separately created objects therefore refer to different keys even if they contain the same fields.
`Map` uses `SameValueZero` equality: values such as `NaN` match themselves, and positive and negative zero are treated as the same key. Object and function keys match only when they are the same reference.
A `Map` iterates entries in insertion order. Updating an existing key does not move it to the end, while deleting and then re-adding that key creates a new position at the end.
Object property keys are strings or symbols, so converting a `Map` with arbitrary keys can coerce keys and cause collisions or loss of key identity. Conversion also requires an explicit policy for values that cannot be represented as ordinary object properties.
JavaScript Practical and Coding Interview Questions
Problem: Return the entries of a Map as a regular array and log the result.
const scores = new Map([['Ada', 10], ['Lin', 9]]);
const entries = Array.from(scores.entries());
console.log(entries);Problem: Create a Map from an array of name-score pairs, then look up and log one score.
const entries = [['Ada', 10], ['Lin', 9]];
const scores = new Map(entries);
console.log(scores.get('Ada'));Problem: Convert a plain object into a Map using its own enumerable properties, then read one value.
const settings = { theme: 'dark', compact: true };
const settingsMap = new Map(Object.entries(settings));
console.log(settingsMap.get('theme'));Problem: Count how many times each word appears in the provided array using a `Map`, then log the count for `pear`.
const words = ["pear", "plum", "pear", "apple", "plum", "pear"];
const counts = new Map();
for (const word of words) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log(counts.get("pear"));Problem: Group the records by their `category` property in a `Map`, preserving input order within each group. Log the names in the `fruit` group.
const records = [
{ name: "pear", category: "fruit" },
{ name: "carrot", category: "vegetable" },
{ name: "plum", category: "fruit" }
];
const groups = new Map();
for (const record of records) {
if (!groups.has(record.category)) groups.set(record.category, []);
groups.get(record.category).push(record.name);
}
console.log(groups.get("fruit"));Problem: Return the two distinct indexes whose fees total the target, or null if no pair exists. Use a Map so each value is checked against the complement seen so far.
function findFeePair(fees, target) {
const earlierIndexByFee = new Map();
for (let index = 0; index < fees.length; index += 1) {
const complement = target - fees[index];
if (earlierIndexByFee.has(complement)) {
return [earlierIndexByFee.get(complement), index];
}
earlierIndexByFee.set(fees[index], index);
}
return null;
}
console.log(findFeePair([275, 420, 325, 80], 600));