By the end of this lesson, you will be able to create a JavaScript Set, add and remove unique values, test membership, and choose when a Set is better than an array.
What it is
A Set is a built-in collection that stores unique values. When you add a value that is already present, the Set ignores the duplicate. Sets remember the order in which values were first inserted, and they can hold any value: numbers, strings, booleans, objects, functions, or even other collections.
The comparison rule is SameValueZero. This means NaN is treated as equal to NaN, and +0 and -0 are treated as the same value. Objects are compared by reference, not by their contents.
Related terms: iterable, Map, WeakSet, array, uniqueness.
Why it matters
- Remove duplicates from arrays quickly.
- Check membership faster than scanning an array with
includes(). - Represent collections where duplicates make no sense, such as tags, user IDs, or visited nodes.
- Iterate unique values in insertion order.
- Combine with spread syntax to convert a Set back into an array.
Syntax or steps
Create a Set with new Set() or new Set(iterable).
const s = new Set();
const t = new Set([1, 2, 2]); // {1, 2}
Use these methods:
add(value)inserts a value and returns the Set.has(value)returnstrueif the value exists.delete(value)removes a value and returnstrueif it was present.clear()removes all values.sizegives the number of unique values.
Iterate with for...of, forEach(), or convert with [...mySet].
Example
const tags = new Set(["js", "css", "js"]);
tags.add("html");
tags.add("css"); // ignored, already present
console.log(tags.size); // 3
console.log(tags.has("js")); // true
tags.delete("css");
console.log(tags.has("css")); // false
for (const tag of tags) {
console.log(tag);
}
const uniqueNumbers = [...new Set([1, 2, 2, 3, 3])];
console.log(uniqueNumbers); // [1, 2, 3]
Part-by-part explanation:
- The constructor receives an array with a duplicate
"js", so the Set stores only one copy. add("html")inserts a new unique value.add("css")is ignored because"css"is already in the Set.sizereports three remaining values:"js","css", and"html".delete("css")removes an existing value.- The
for...ofloop iterates over the remaining unique values. [...new Set(...)]converts a Set back into an array.
Common mistakes
- Assuming objects with the same contents are equal.
new Set([{id: 1}, {id: 1}])has size2because the objects are different references. Use primitive keys or aMapinstead. - Trying to access a Set by index.
mySet[0]isundefined. Convert to an array first or iterate over the Set. - Using a Set when you need key-value pairs. A Set stores values only. If each value needs associated data, use a
Map. - Forgetting that
add()returns the Set. This allows chaining, such ass.add(1).add(2), but it does not return a boolean.
When to use it
| Need | Use | Why |
|---|---|---|
| Unique values only | Set |
Duplicates are ignored automatically. |
| Fast membership checks | Set |
has() is usually better than scanning an array. |
| Key-value pairs | Map |
Each key can store an associated value. |
| Ordered list with duplicates | Array |
Arrays preserve duplicates and support index access. |
Practice
Guided exercise: Given [1, 2, 2, 3, 3, 3], create a Set and convert it back to an array.
Expected output: [1, 2, 3].
Challenge: Remove duplicate objects by their id property.
Hint: map the objects to their IDs, create a Set from those IDs, then filter the original array.
Quick check
What does new Set([NaN, NaN]).size return?
It returns 1, because a Set treats NaN as the same value.
Summary
A JavaScript Set is a collection of unique values that preserves insertion order and uses value-based uniqueness rules. It is ideal for removing duplicates and checking membership. When you need key-value data or duplicate entries, choose Map or Array instead.