JavaScript — Sets
A Set holds no duplicates
const ids = new Set([1, 2, 2, 3, 3, 3]);
console.log(ids); // Set(3) {1, 2, 3}
Adding an existing value does nothing:
ids.add(1); // ignored — already present
ids.add(4); // added
ids.has(2); // true membership check
ids.delete(2); // true (was there)
ids.size; // 3
The killer use: deduplicating arrays
const tags = ["css", "js", "css", "html", "js"];
const unique = [...new Set(tags)];
// ["css", "js", "html"]
One line replaces the manual filter-and-check dance. Works on primitives by value:
[...new Set("mississippi")].join(""); // "mispi"
Why not just includes()?
arr.includes(x); // scans the array — O(n)
set.has(x); // hash lookup — effectively O(1)
For "have I seen this before?" checks inside loops, Sets scale where includes crawls:
const seen = new Set();
for (const row of bigData) {
if (seen.has(row.id)) continue; // instant skip
seen.add(row.id);
process(row);
}
Iteration preserves insertion order
for (const id of ids) console.log(id);
[...ids]; // back to array
ids.forEach(v => …); // also available
Set algebra
const a = new Set([1, 2, 3]);
const b = new Set([3, 4]);
// union — everything in either
const union = new Set([...a, ...b]); // {1,2,3,4}
// intersection — in both
const both = [...a].filter(x => b.has(x)); // [3]
// difference — in a but not b
const onlyA = [...a].filter(x => !b.has(x)); // [1,2]
WeakSet (one paragraph)
WeakSet holds only objects and lets them be garbage-collected when unused elsewhere. Niche: marking objects as processed without preventing cleanup.
Gotchas: no index access (
set[0]meaningless — convert to array first); object equality is by reference, so{a:1}added twice stores twice.
Mini Practice
- Deduplicate an array of names three ways: Set, filter+indexOf, reduce
- Time
includesvshasover 100k lookups (console.time) - Build "mutual friends": intersection of two friend sets
- Track unique site visitors per day with add/size
- Union two tag lists into a sorted unique array
Next: maps →
Related Topics
Frequently Asked Questions about Sets
What is Sets in JavaScript?
Sets is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Sets?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Sets.
Why is Sets important in JavaScript?
Sets is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.