JS Sets
Creating a Set
A Set is created with new Set(), optionally passing an iterable like an array, and any duplicate values in that initial array are automatically dropped, leaving only unique entries.
Note: Passing an existing array into new Set() is a quick, common way to remove duplicate values from that array.
Warning: A Set preserves the type of its values strictly, the number 1 and the string 1 are treated as two different, distinct entries.
Example: Creating a Set
const nums = new Set([1, 2, 2, 3]);
console.log(nums); // duplicates dropped: {1, 2, 3}
add, delete, and has
add() inserts a new value into the Set, delete() removes a specific value and returns whether it was actually present, and has() checks whether a given value already exists in the Set.
Note: has() runs very efficiently on a Set, making it a great choice for checking membership in a large collection compared to array.includes().
Warning: Calling add() with a value already in the Set does nothing and does not throw an error, the Set silently stays unchanged.
Example: add, delete, and has
const nums = new Set();
nums.add(1);
nums.add(2);
console.log(nums.has(1));
nums.delete(1);
console.log(nums.has(1));
The size Property
A Set's size property reports how many unique values it currently contains, functioning the same conceptual role as length does for arrays and strings. Unlike array length, size is read-only and always reflects the Set's actual current contents.
Note: Comparing an array's length against a Set built from it, like new Set(array).size, is a quick way to check if the array had any duplicates.
Warning: size is a property, not a method, it's accessed without parentheses, mySet.size, not mySet.size().
Example: The size Property
const nums = new Set([1, 2, 3]);
console.log(nums.size);
Iterating a Set
Sets are iterable, letting you loop through every unique value using for...of, in the same order the values were originally added. This insertion-order guarantee makes Sets predictable to iterate even though they're built around uniqueness rather than position.
Note: Sets maintain insertion order, so iterating one always visits values in the exact order they were first added.
Warning: You cannot use a regular indexed for loop, like mySet[i], on a Set, it has no index-based access at all.
Example: Iterating a Set
const nums = new Set([1, 2, 3]);
for (let n of nums) {
console.log(n);
}
Set vs Array
A Set automatically enforces uniqueness and offers very fast membership checks with has(), while an array allows duplicates and supports rich methods like map, filter, and indexed access that Sets don't have.
Note: Convert a Set back to an array with the spread operator, [...mySet], whenever you need array-specific methods like map or filter.
Warning: Choosing a Set purely for its uniqueness but then needing frequent array-style operations often means converting back and forth repeatedly, consider whether an array with manual duplicate checks might be simpler.
Example: Set vs Array
const set = new Set([1, 2, 2, 3]);
const arr = [1, 2, 2, 3];
console.log(set.size, arr.length); // 3 vs 4
console.log(set.has(2), arr.indexOf(2) !== -1);
- Trying to access a Set's items by index, like mySet[0], Sets have no index-based access, only iteration and has().
- Forgetting that a Set's size is checked with the size property, not length like an array.
- Assuming adding a duplicate value throws an error, it doesn't, add() on an existing value simply has no effect.
- A Set stores a collection of values where every value is guaranteed to be unique.
- add(), delete(), and has() are the primary methods for managing a Set's contents.
- Sets can be iterated with for...of and converted to arrays with the spread operator when array methods are needed.
Set has been supported in all major browsers since 2015 and is a fully standard part of modern JavaScript.
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS Dates
- JS Math
- JS Conditionals
- JS Switch
- JS Loop For
- JS Loop While
- JS Iterables
- JS Sets
- JS Maps
- JS typeof
- JS Type Conversion
- JS Destructuring
- JS Arrow Functions
- JS Classes
- JS Modules
- JS Promises
- JS Async/Await
- JS DOM
- JS DOM Methods
- JS Events Advanced
- JS DOM Navigation
- JS DOM Collections
- JS Async Callbacks
- JS Async Parallel
- JS Date Set
- JS Set Logic