JavaScript Set Data Structure
A Set in JavaScript is a built-in object that lets you store unique values of any type—primitive or object references. Sets are useful when you want to ensure no duplicates exist in your collection.
Common use cases:
- Deduplication: Eliminate duplicate values from arrays.
- Efficient lookup: Quickly check whether an item exists.
- Storing unique elements: Ensure uniqueness in lists like tags, IDs, or filters.
- Set operations: Perform union, intersection, and difference using Sets.
Understanding the Set Data Structure
A Set is a JavaScript object that stores a collection of unique values. It automatically removes duplicates and provides fast operations for checking the presence of an item.
Here’s the basic syntax to create a Set:
const mySet = new Set();
const mySet = new Set();
- mySet: A new Set instance assigned to a variable.
- new Set(): Creates an empty Set that you can populate with values later.
You can also create a Set from an array or another iterable:
const numbers = [1, 2, 3, 3, 4, 4];
const uniqueNumbers = new Set(numbers);
console.log(uniqueNumbers); // Output: Set(4) {1, 2, 3, 4}
const numbers = [1, 2, 3, 3, 4, 4];
const uniqueNumbers = new Set(numbers);
console.log(uniqueNumbers); // Output: Set(4) {1, 2, 3, 4}
As shown above, duplicate values are automatically removed when creating a Set from an array. This makes Set a handy tool for deduplicating data.
You can store any type of value in a Set—including strings, numbers, booleans, objects, and more. However, keep in mind that objects are compared by reference, not by value.
Creating a Set
In JavaScript, a Set can be created using the new Set() constructor. Sets can be initialized empty or with values from an iterable like an array.
1. Creating an Empty Set
You can create an empty set and add values later using the add() method.
const mySet = new Set();
mySet.add(10);
mySet.add('hello');
console.log(mySet); // Output: Set(2) {10, 'hello'}
const mySet = new Set();
mySet.add(10);
mySet.add('hello');
console.log(mySet); // Output: Set(2) {10, 'hello'}
2. Creating a Set from an Array
You can also initialize a set with values from an array. Duplicate values are automatically removed.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const numberSet = new Set(numbers);
console.log(numberSet); // Output: Set(5) {1, 2, 3, 4, 5}
const numbers = [1, 2, 2, 3, 4, 4, 5];
const numberSet = new Set(numbers);
console.log(numberSet); // Output: Set(5) {1, 2, 3, 4, 5}
3. Creating a Set from a String
Since a string is an iterable, you can pass it to new Set() to get a set of unique characters.
const charSet = new Set('hello');
console.log(charSet); // Output: Set(4) {'h', 'e', 'l', 'o'}
const charSet = new Set('hello');
console.log(charSet); // Output: Set(4) {'h', 'e', 'l', 'o'}
This is a quick way to extract unique characters from a word or phrase.
4. Set Ignores Duplicate Values
If you try to add a duplicate value, it will be ignored. The size of the set remains unchanged.
const set = new Set();
set.add(1);
set.add(1);
set.add('1');
set.add('1');
console.log(set); // Output: Set(2) {1, '1'}
const set = new Set();
set.add(1);
set.add(1);
set.add('1');
set.add('1');
console.log(set); // Output: Set(2) {1, '1'}
In this example, 1 (number) and '1' (string) are treated as different values, but duplicates of each are ignored.
Accessing Set Elements
Unlike arrays, Set objects do not use numeric indexes. Instead, you access elements using methods like has(), or by iterating through the Set.
1. Checking for an Element with has()
Use the has() method to check whether a specific value exists in a Set.
const fruits = new Set(['apple', 'banana', 'cherry']);
console.log(fruits.has('banana')); // Output: true
console.log(fruits.has('orange')); // Output: false
const fruits = new Set(['apple', 'banana', 'cherry']);
console.log(fruits.has('banana')); // Output: true
console.log(fruits.has('orange')); // Output: false
has() is case-sensitive and performs a strict comparison.
2. Iterating with for...of
You can use a for...of loop to iterate through all the elements in a Set.
const colors = new Set(['red', 'green', 'blue']);
for (const color of colors) {
console.log(color);
}
// Output:
// red
// green
// blue
const colors = new Set(['red', 'green', 'blue']);
for (const color of colors) {
console.log(color);
}
// Output:
// red
// green
// blue
This is the most common way to loop through Set elements.
3. Iterating with forEach()
Sets also support the forEach() method, just like arrays.
const numbers = new Set([1, 2, 3]);
numbers.forEach((value) => {
console.log(value);
});
// Output:
// 1
// 2
// 3
const numbers = new Set([1, 2, 3]);
numbers.forEach((value) => {
console.log(value);
});
// Output:
// 1
// 2
// 3
Note that the forEach() callback receives the same value twice: once as the value and once as the key (to stay consistent with the Map API).
4. Converting Set to Array (for Indexing)
Since Sets don’t support direct indexing, you can convert them to an array if you need to access elements by index.
const letters = new Set(['a', 'b', 'c']);
const lettersArray = Array.from(letters);
console.log(lettersArray[1]); // Output: 'b'
const letters = new Set(['a', 'b', 'c']);
const lettersArray = Array.from(letters);
console.log(lettersArray[1]); // Output: 'b'
Use Array.from() or the spread operator [...set] to convert a Set to an array.
Modifying Set Elements
While a Set does not support direct modification of individual elements (like using indexes in arrays), you can modify the contents by adding, deleting, or clearing elements. Here's how:
1. Adding Elements with add()
Use the add() method to insert a new element into a Set. If the value already exists, it won’t be added again.
const set = new Set();
set.add('apple');
set.add('banana');
set.add('apple'); // Duplicate, will be ignored
console.log(set); // Output: Set(2) {'apple', 'banana'}
const set = new Set();
set.add('apple');
set.add('banana');
set.add('apple'); // Duplicate, will be ignored
console.log(set); // Output: Set(2) {'apple', 'banana'}
Sets automatically prevent duplicates. No error is thrown if a value already exists.
2. Deleting Elements with delete()
The delete() method removes a specific value from the Set. It returns true if the value was removed, or false if it didn’t exist.
const set = new Set(['apple', 'banana', 'cherry']);
set.delete('banana'); // true
set.delete('grape'); // false (not found)
console.log(set); // Output: Set(2) {'apple', 'cherry'}
const set = new Set(['apple', 'banana', 'cherry']);
set.delete('banana'); // true
set.delete('grape'); // false (not found)
console.log(set); // Output: Set(2) {'apple', 'cherry'}
This allows you to remove specific items cleanly.
3. Clearing All Elements with clear()
Use clear() to remove all elements from a Set.
const set = new Set(['apple', 'banana', 'cherry']);
set.clear();
console.log(set); // Output: Set(0) {}
const set = new Set(['apple', 'banana', 'cherry']);
set.clear();
console.log(set); // Output: Set(0) {}
This is useful for resetting the Set.
4. Replacing an Element
Since Sets don’t use indexes, replacing an element requires deleting the old value and adding a new one.
const set = new Set(['apple', 'banana', 'cherry']);
// Replace 'banana' with 'blueberry'
if (set.has('banana')) {
set.delete('banana');
set.add('blueberry');
}
console.log(set); // Output: Set(3) {'apple', 'cherry', 'blueberry'}
const set = new Set(['apple', 'banana', 'cherry']);
// Replace 'banana' with 'blueberry'
if (set.has('banana')) {
set.delete('banana');
set.add('blueberry');
}
console.log(set); // Output: Set(3) {'apple', 'cherry', 'blueberry'}
Sets are not indexed, so replacing elements must be done manually like this.
Frequently Asked Questions
What is a Set in JavaScript?
What is a Set in JavaScript?
A Set is a collection of unique values. It automatically eliminates duplicates and stores only distinct elements.
How do you create a Set in JavaScript?
How do you create a Set in JavaScript?
Create a set with the constructor: let mySet = new Set(); or initialize it with values: let mySet = new Set([1, 2, 3]);.
How can you add and remove elements from a Set?
How can you add and remove elements from a Set?
Use add() to insert elements, like mySet.add(5). Remove elements with delete(), such as mySet.delete(5).
Can Sets store objects or other data types?
Can Sets store objects or other data types?
Yes, Sets can contain any data type — primitives, objects, arrays, and functions — as long as the values are unique.
How do you check if a Set contains a specific element?
How do you check if a Set contains a specific element?
Use the has() method, like mySet.has(3), which returns true if the element exists in the set.
What's Next?
Up next: JavaScript Set methods – powerful tools for managing unique values, performing set operations, and enhancing data handling efficiency.