Lesson 8 of 30
A collection that automatically refuses duplicates — useful anytime the real question is 'have I seen this before,' not 'how many times.'
8 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
This topic is about judgment and practical tradeoffs more than a single right answer — a mock interview is the better way to test yourself on it.
Be interviewed on this →Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
Imagine you're running the guest list for a small party. Someone can only appear on that list once. If a friend tries to add "Maria" a second time, you don't write "Maria" twice — she's already on the list, so nothing changes.
A Set works exactly like that guest list. It's a collection of values where every value is allowed to appear only once. Try to add something that's already in there, and the Set just doesn't add it again. No error, no duplicate. It quietly stays the same.
This is different from an array, which is happy to hold the same value as many times as you push it in. An array is more like a sign-in sheet at the door — everyone who walks in gets a new line, even if they walked in twice.
Sets are useful anytime your real question is "have I seen this before," not "how many times have I seen it" or "in what order did I see them." Removing duplicates from a list, checking if something already exists, tracking which items you've visited — all Set territory.
// A Set can start empty and grow with .add(), one value at a time.
const guestList = new Set();
guestList.add("Maria");
guestList.add("Jordan");
guestList.add("Maria"); // trying to add Maria again — the Set ignores it
console.log(guestList.size); // 2, not 3
console.log(guestList.has("Maria")); // true — instant check, like a hash map
// A common real use: removing duplicates from an array in one line.
const namesWithDuplicates = ["Maria", "Jordan", "Maria", "Sam", "Jordan"];
const uniqueNames = [...new Set(namesWithDuplicates)];
console.log(uniqueNames); // ["Maria", "Jordan", "Sam"]
.add() on an existing value isn't an error. It's easy to expect a warning or exception. Nothing happens — silently doing nothing IS the correct, intended behavior.A Set uses the same instant-lookup trick as the hash map you just met — under the hood, it's hashing values to check "is this here already" in roughly constant time, not by scanning the whole collection. Think of it as a hash map that only cares about keys, not values.