Picture a signup log that keeps growing all day. Every time a new signup arrives, you want to know whether that person has signed up before. You could scan every earlier signup each time, but the work piles up: a log twice as long takes four times as long to check. Interviewers love problems like this, because there’s an obvious slow solution and a much faster one that comes from asking a better question.
The better question is: what do I need to remember about the items I’ve already seen? If the answer is “whether I’ve seen this value”, a Set remembers it. If you need a count or a position, a Map stores it next to the value:
const seen = new Set();
seen.add("[email protected]");
seen.has("[email protected]"); // Returns true
const views = new Map();
views.set("/pricing", (views.get("/pricing") ?? 0) + 1);
views.get("/pricing"); // Returns 1
Both answer lookups in O(1) time on average. Reading n items and doing a constant number of lookups for each one brings the whole job down from O(n²) to O(n). The price is O(n) extra memory for what you’ve stored. Say that tradeoff out loud in an interview: it shows you know what your solution costs, not just that it works.
Why Not a Plain Object?
Plenty of JavaScript code, and plenty of AI-generated code, uses {} as a dictionary. It mostly works, until a key collides with something every object already has:
const counts = {};
counts["constructor"]; // Returns ƒ Object() { [native code] }, not undefined
counts["__proto__"] = 1; // Changes the prototype instead of adding a key
A Map has no inherited keys, accepts any value as a key, remembers insertion order, and tells you its size with .size. When keys come from user data, such as tags, usernames, or search terms, reach for a Map or a Set.
What JavaScript Doesn’t Include
Map and Set are built in, but a heap, a deque, and a sorted map aren’t. In production code, developers usually reach for a library such as heap-js, mnemonist, or @datastructures-js/priority-queue. Later courses show when to use one, and how to write a small heap yourself when an interviewer asks you to.
In this section, you’ll practice the hashing pattern in two ways: solving a problem from scratch, and reviewing code someone else wrote. Watch for the moment a slow rescan can turn into a single lookup.