JavaScript Set Object: Complete Guide
Learn the JavaScript Set object for storing unique values of any type. Covers add, delete, has, iteration, removing duplicates, and set operations.
A Set is a built-in JavaScript collection that stores unique values. Unlike an array, a Set automatically prevents duplicates. Add the same value twice and only one copy is kept. This makes Set perfect for tracking unique items, removing duplicates, and membership testing.
const tags = new Set();
tags.add("javascript");
tags.add("web");
tags.add("javascript"); // Duplicate -- silently ignored
console.log(tags.size); // 2
console.log(tags.has("javascript")); // trueBasic Operations
add(), delete(), has(), clear(), and size are the core methods you will use for almost every Set. Adding a value and checking membership are the two most common operations:
const colors = new Set();
colors.add("red");
colors.add("blue");
colors.add("green");
console.log(colors.size); // 3
console.log(colors.has("blue")); // trueRemoving a single value or clearing the whole Set works the same way it does on a Map, and size always reflects the current count:
colors.delete("blue");
console.log(colors.has("blue")); // false
console.log(colors.size); // 2
colors.clear();
console.log(colors.size); // 0The add() method returns the Set itself, which lets you chain several additions in a single expression instead of repeating the variable name:
const letters = new Set();
letters.add("a").add("b").add("c");
console.log(letters.size); // 3Creating a Set from an Array
Pass any iterable, such as an array, string, or another Set, to the constructor to populate a new Set with its values in one step:
const numbers = new Set([1, 2, 3, 3, 4, 4, 5]);
console.log(numbers.size); // 5 (duplicates removed)
console.log([...numbers]); // [1, 2, 3, 4, 5]This is the most common Set pattern: converting an array to a Set to strip duplicates, then spreading back to an array.
Removing Duplicates from an Array
The classic one-liner for deduplication:
const items = ["apple", "banana", "apple", "orange", "banana"];
const unique = [...new Set(items)];
console.log(unique); // ["apple", "banana", "orange"]This works for primitive values. For arrays of objects, duplicates are determined by reference identity, not property values. Two objects with the same properties are different references and will both be kept.
Iterating Over a Set
Set is iterable. You can use for...of, forEach(), values(), and keys():
const fruits = new Set(["apple", "banana", "orange"]);
for (const fruit of fruits) {
console.log(fruit);
}
fruits.forEach(value => {
console.log(value);
});Set's keys() and values() are identical; both return the values. entries() returns value-value pairs, which exists for consistency with Map's API so you can use the same iteration patterns for both.
Converting Between Set and Array
| Direction | Code |
|---|---|
| Array → Set | new Set(array) |
| Set → Array | [...set] or Array.from(set) |
These conversions are fast and common. You can go back and forth as needed, using Set when you need uniqueness checks and Array when you need indexed access or array methods.
Set Composition Methods
Modern JavaScript (ES2024+) provides native set operation methods, available in all current browsers and Node.js since mid-2024. These accept any set-like object (an object with size, has(), and keys()):
const a = new Set([1, 2, 3, 4]);
const b = new Set([3, 4, 5, 6]);
console.log(a.union(b)); // Set {1, 2, 3, 4, 5, 6}
console.log(a.intersection(b)); // Set {3, 4}
console.log(a.difference(b)); // Set {1, 2}
console.log(a.isSubsetOf(b)); // falseBefore these built-in methods, you would implement set operations manually using filter and spread. The native methods are cleaner and more performant. For more context on how Set compares to arrays for these patterns, see the article on /javascript/set-vs-array-in-javascript-complete-guide.
Practical Use: Tracking Seen Items
A common pattern is using a Set to track which items have already been processed:
const processed = new Set();
function handleItem(id, data) {
if (processed.has(id)) {
return; // Skip duplicates
}
processed.add(id);
// ... process the data
}This is cleaner than using an array with includes() because has() is faster on large collections and the intent is clearer.
Value Equality
Set uses the SameValueZero algorithm, meaning NaN is treated as equal to NaN, even though NaN !== NaN:
const s = new Set();
s.add(NaN);
s.add(NaN);
console.log(s.size); // 1 (not 2)
console.log(s.has(NaN)); // trueObject values follow a different rule than primitives, since equality is checked by reference, not by the values inside the object:
const s = new Set();
s.add({ id: 1 });
s.add({ id: 1 });
console.log(s.size); // 2 (different object references)Common Mistake: Set Has No Index Access
A Set has no concept of position, only membership, so bracket notation with a number does not do what an array user would expect. Unlike arrays, you cannot access a Set element by position:
const s = new Set(["a", "b", "c"]);
// Wrong -- Sets do not support index access
// console.log(s[0]); // undefined
// Correct -- convert to array first if you need indexing
console.log([...s][0]); // "a"Set is designed for uniqueness and membership, not positional access. If you need both, convert to an array when you need indexed operations. For removing duplicates from arrays, combining Set with the spread operator as shown here is the standard approach covered in more detail in the article on /javascript/removing-duplicates-from-arrays-in-javascript-guide.
Rune AI
Key Insights
- A Set stores unique values of any type -- duplicates are silently ignored.
- Use add() to insert, delete() to remove, and has() to check membership.
- The size property gives the count, and iteration preserves insertion order.
- Convert between Set and Array with the constructor and spread operator.
- Modern Set composition methods (union, intersection, difference) work across Set-like objects.
Frequently Asked Questions
What is a Set in JavaScript?
How do I remove duplicates from an array using Set?
Does Set preserve insertion order?
Conclusion
Set is the right collection when you need uniqueness guarantees without manual checks. Use it for deduplication, membership testing, and tracking collections of unique items. The built-in methods and iteration support make it a clean replacement for array-based workarounds.
More in this topic
JavaScript While Loop Explained: A Complete Guide
A while loop repeats code as long as a condition stays true. Learn the syntax, see practical examples, and understand when a while loop is the right choice over a for loop.
JavaScript Loops Tutorial: for, while, do while
Loops let JavaScript repeat code without writing it twice. Learn the three core loop types, what each one does, and when to choose one over another.
How to Loop Through Arrays Using JS for Loops Guide
Looping through arrays is the most practical use of JavaScript for loops. Learn how to access each element by index, avoid off-by-one errors, and choose between for, for...of, and forEach.