Sets

Updated · 6 min read
mediumES2026javascriptsetcollectionsunique

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() or new Set(iterable): new Set([9, 10, 9]) holds 9 and 10.
  • add(value), has(value), delete(value), clear() and the size property.
  • Remove duplicates from an array: [...new Set(array)].
  • Values keep insertion order; loop with for...of or forEach.
  • Uniqueness uses SameValueZero: like ===, except NaN equals NaN. Objects are unique by reference.

Creating a Set

Syntax

syntax.js
const set = new Set();               // empty
const set2 = new Set(iterable);      // from an array, string, Map keys...

Example

create.js▶ Try it
const grades = new Set([9, 10, 9, 11, 10]);
console.log(grades);
console.log(grades.size);
 
const letters = new Set("Anamaneni");
console.log(letters);
Output
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

MethodDescription
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.
sizeA 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.
methods.js▶ Try it
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);
Output
2
true
false
true
false
Set(1) {'Navika'}
0

Removing Duplicates

The most common use of a Set is turning a list with duplicates into a list of unique values:

unique.js▶ Try it
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);
Output
['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:

iterate.js▶ Try it
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));
Output
SIBLING
STAFF
EARLY
['sibling', 'staff', 'early']
forEach: SIBLING
forEach: STAFF
forEach: EARLY

Re-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):

compare.js▶ Try it
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);
Output
Set(4) {1, '1', NaN, 0}
2
3

Explanation: 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:

reminders.js▶ Try it
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]);
Output
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
first-duplicate.js▶ Try it
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"]));
Output
Advitha
null

Quick check: Sets

3 questions
1What is new Set([1, 2, 2, 3]).size?
2How do you remove duplicates from an array arr?
3Does a Set treat two objects with identical properties as one value?

Key Takeaways

TaskCode
Createnew Set([1, 2])
Add / check / removes.add(x), s.has(x), s.delete(x)
Counts.size
Unique array[...new Set(arr)]
To arrayArray.from(s)

Was this tutorial helpful?

Lesson 46 of 139