Sets
A Set is a built-in collection that stores unique values: each value can appear only once, and adding it again has no effect. Sets answer "have I seen this before?" instantly, remove duplicates from a list in one line, and keep values in the order they were first added. The Fee Tracker uses them for the list of grades that have payments, the students who already got a reminder, and the codes that are valid.
In One Minute
- Create with
new Set()ornew Set(iterable):new Set([9, 10, 9])holds9and10. add(value),has(value),delete(value),clear()and thesizeproperty.- Remove duplicates from an array:
[...new Set(array)]. - Values keep insertion order; loop with
for...oforforEach. - Uniqueness uses SameValueZero: like
===, exceptNaNequalsNaN. Objects are unique by reference.
Creating a Set
Syntax
const set = new Set(); // empty
const set2 = new Set(iterable); // from an array, string, Map keys...Example
const grades = new Set([9, 10, 9, 11, 10]);
console.log(grades);
console.log(grades.size);
const letters = new Set("Anamaneni");
console.log(letters);Set(3) {9, 10, 11}
3
Set(6) {'A', 'n', 'a', 'm', 'e', 'i'}Explanation: duplicates are dropped as the set is built. A string is iterable, so new Set("Anamaneni") collects its unique characters; "A" and "a" are different values. size (a property, not a method) gives the count.
Set Methods
| Method | Description |
|---|---|
add(value) | It is used to add a value; returns the set, so calls can be chained. |
has(value) | It is used to check whether the value is in the set. |
delete(value) | It is used to remove a value; returns true if it was there. |
clear() | It is used to remove every value. |
size | A property holding the number of values. |
forEach(fn) | It is used to run fn for each value, in insertion order. |
values() / keys() | It is used to get an iterator over the values (both are the same for sets). |
entries() | It is used to get [value, value] pairs, for symmetry with Map. |
union, intersection, difference... | Combining sets (ES2025), covered in the next lesson. |
const reminded = new Set();
reminded.add("Navika").add("Srihitha");
reminded.add("Navika");
console.log(reminded.size);
console.log(reminded.has("Srihitha"));
console.log(reminded.has("Advitha"));
console.log(reminded.delete("Srihitha"));
console.log(reminded.delete("Srihitha"));
console.log(reminded);
reminded.clear();
console.log(reminded.size);2
true
false
true
false
Set(1) {'Navika'}
0Removing Duplicates
The most common use of a Set is turning a list with duplicates into a list of unique values:
const payments = [
{ name: "Navika", grade: 9 },
{ name: "Advitha", grade: 11 },
{ name: "Navika", grade: 9 },
{ name: "Srihitha", grade: 11 },
];
const uniqueNames = [...new Set(payments.map((p) => p.name))];
console.log(uniqueNames);
const gradeCount = new Set(payments.map((p) => p.grade)).size;
console.log(gradeCount);['Navika', 'Advitha', 'Srihitha']
2[...new Set(array)] keeps the first occurrence of each value, in order. Array.from(new Set(array)) does the same. If you only need the count of unique values, .size is enough.
Iterating
Sets remember the order in which values were first added:
const codes = new Set(["SIBLING", "STAFF"]);
codes.add("EARLY");
codes.add("SIBLING");
for (const code of codes) {
console.log(code);
}
console.log([...codes].map((c) => c.toLowerCase()));
codes.forEach((value) => console.log("forEach:", value));SIBLING
STAFF
EARLY
['sibling', 'staff', 'early']
forEach: SIBLING
forEach: STAFF
forEach: EARLYRe-adding "SIBLING" didn't move it. To use array methods such as map or filter, spread the set into an array first (or use iterator helpers, covered later in the course).
How Sets Compare Values
Sets use the SameValueZero comparison: the same as ===, except that NaN is considered equal to NaN (and 0 equals -0):
const values = new Set([1, "1", NaN, NaN, 0, -0]);
console.log(values);
const people = new Set();
people.add({ name: "Navika" });
people.add({ name: "Navika" });
console.log(people.size);
const navika = { name: "Navika" };
people.add(navika);
people.add(navika);
console.log(people.size);Set(4) {1, '1', NaN, 0}
2
3Explanation: 1 and "1" are different types, so both stay. The two NaNs collapse into one, and 0 and -0 are treated as the same. The two { name: "Navika" } literals are different objects, so both are kept: a Set doesn't look inside objects. Adding the same object (navika) twice keeps only one copy.
In Practice
The Fee Tracker sends reminders only once per student per day, and only for valid discount codes. Sets make both checks direct:
const VALID_CODES = new Set(["SIBLING", "STAFF", "EARLY"]);
const remindedToday = new Set();
function remind(student) {
if (remindedToday.has(student.name)) return `${student.name}: already reminded`;
remindedToday.add(student.name);
const code = student.code?.toUpperCase();
const note = VALID_CODES.has(code) ? ` (discount ${code})` : "";
return `${student.name}: reminder sent${note}`;
}
console.log(remind({ name: "Navika", code: "sibling" }));
console.log(remind({ name: "Srihitha", code: "BOGUS" }));
console.log(remind({ name: "Navika" }));
console.log([...remindedToday]);Navika: reminder sent (discount SIBLING)
Srihitha: reminder sent
Navika: already reminded
['Navika', 'Srihitha']Common Mistakes
Using length. Sets have size, not length.
Expecting objects with the same contents to be deduplicated. They are different references. Deduplicate by a key instead.
Reading by index. set[0] is undefined; sets have no indexes. Spread to an array, or iterate.
Forgetting to convert back. new Set(arr).map(...) fails: Sets have no map. Use [...new Set(arr)].map(...).
Practice
Challenge: Write firstDuplicate(names) that returns the first name that appears a second time while reading the list from left to right, or null if every name is unique. Use a Set.
Show solution
function firstDuplicate(names) {
const seen = new Set();
for (const name of names) {
if (seen.has(name)) return name;
seen.add(name);
}
return null;
}
console.log(firstDuplicate(["Navika", "Advitha", "Srihitha", "Advitha", "Navika"]));
console.log(firstDuplicate(["Navika", "Advitha"]));Advitha
nullKey Takeaways
| Task | Code |
|---|---|
| Create | new Set([1, 2]) |
| Add / check / remove | s.add(x), s.has(x), s.delete(x) |
| Count | s.size |
| Unique array | [...new Set(arr)] |
| To array | Array.from(s) |
Was this tutorial helpful?