JavaScript lesson · 16 min

JavaScript Set

Store unique values, remove duplicates, and check membership quickly.

Code runs locally in your browser

What you will practice

  • Create a Set from an array.
  • Remove duplicate values.
  • Check whether a value exists.

What this means

A Set is a collection where each value appears only once. If you add the same value twice, the Set still keeps one copy.

Sets are perfect when uniqueness matters more than counting every occurrence.

A Set has methods such as `add`, `has`, and `delete`, plus a `size` property for the number of unique values.

If this is your first time seeing this

Set is for uniqueness. If you only want one copy of each value, Set is often the simplest answer.

Set is not about counting how many times something appeared. It is about whether it appears at least once.

Mini glossary

Set
A collection that stores each value only once.
has
Checks whether a Set contains a value.
size
The number of unique values in the Set.

Example from everyday life

A Set is like a guest list at the door. If Mira is already on the list, writing Mira again does not create a second person. The list cares about unique names.

How it works step by step

  1. The code starts with an array that contains duplicate tags.
  2. `new Set(tags)` creates a collection of unique tag values.
  3. `Array.from(uniqueTags)` turns the Set back into an array so it can be displayed.
  4. `has("json")` checks whether the unique collection contains a value.

Where you will use this

  • A duplicate-line remover keeps only unique lines.
  • A filter UI stores selected categories without duplicates.
  • A crawler keeps a Set of visited URLs so it does not process the same page twice.

Before you run the code

Use Set when you care whether a value is present, not how many times it appeared.

If you need counts for every value, Map is usually a better next step.

Common beginner mistakes

  • Using Set when you actually need frequency counts.
  • Expecting duplicate primitive values to be kept.
  • Forgetting to convert a Set back to an array when array methods are needed.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingRemoves duplicate values
WaitingCounts unique values

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Add another duplicate tag and see that the count does not change.
  • Delete one tag with `uniqueTags.delete("seo")`.
  • Convert the Set to an array and sort it.