How to Create a Set
To create a Set, you can use the new Set() syntax:
let mySet = new Set();
You can also initialize a Set with values by passing an array to it:
let numbers = new Set([1, 2, 3, 4, 5]);
console.log(numbers);
Methods of Set in JavaScript
JavaScript Set objects come with several built-in methods to perform various operations. Below are the most commonly used methods:
1. add(value): Adds a new value to the Set.
let mySet = new Set();
mySet.add(1);
mySet.add(2);
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output
Set {1, 2}
2. delete(value): Removes a specific value from the Set.
mySet.delete(1);
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output
Set {2}
3. has(value): Checks if a value exists in the Set.
console.log(mySet.has(2));
console.log(mySet.has(1));

You can also try this code with Online Javascript Compiler
Run Code
Output
true
false
4. clear(): Removes all values from the Set.
mySet.clear();
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output
Set {}
Properties of Set in JavaScript
In addition to the methods, Sets have certain properties that are essential for working with them.
size: Returns the number of unique elements in the Set.
let mySet = new Set([1, 2, 3, 4]);
console.log(mySet.size);

You can also try this code with Online Javascript Compiler
Run Code
Output
4
Symbol.iterator: This property allows Sets to be iterable, so you can loop through the Set’s values using for...of or forEach() methods.
for (let value of mySet) {
console.log(value);
}

You can also try this code with Online Javascript Compiler
Run Code
Output
1, 2, 3, 4
Examples of Methods and Properties
Let’s look at a few more examples to understand Set methods and properties:
Example 1: Using add(), has(), and delete() Methods
let fruits = new Set();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
console.log(fruits.has("Apple"));
console.log(fruits.has("Mango"));
fruits.delete("Banana");
console.log(fruits);

You can also try this code with Online Javascript Compiler
Run Code
Output
true
False
Set { 'Apple', 'Orange' }
Example 2: Using clear() and size Properties
let numbers = new Set([1, 2, 3]);
console.log(numbers.size);
numbers.clear();
console.log(numbers.size);

You can also try this code with Online Javascript Compiler
Run Code
Output
3
0
Example 3: Removing Duplicates from an Array
One of the most common uses of a Set is to remove duplicate values from an array. Since Sets only store unique values, they can easily filter out duplicates.
const duplicateNumbers = [1, 2, 3, 4, 2, 3, 5];
const uniqueNumbers = [...new Set(duplicateNumbers)];
console.log(uniqueNumbers);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3, 4, 5]
In this code:
1. We start with an array `duplicateNumbers` that contains duplicate values.
2. We create a new Set using `new Set(duplicateNumbers)`. The Set automatically removes duplicates.
3. We convert the Set back into an array using the spread operator `[... ]`.
4. The result is a new array `uniqueNumbers` with all duplicates removed.
Example 4: Checking for Unique Characters in a String
Sets can also be used to check if all characters in a string are unique.
function hasUniqueCharacters(str) {
return new Set(str).size === str.length;
}
console.log(hasUniqueCharacters('hello'));
console.log(hasUniqueCharacters('world'));

You can also try this code with Online Javascript Compiler
Run Code
Output:
false
true
In this code:
1. The function `hasUniqueCharacters` takes a string `str` as input.
2. We create a Set from the string using `new Set(str)`. This removes any duplicate characters.
3. We compare the `size` of the Set with the length of the original string.
4. If they are equal, it means all characters in the string are unique. Otherwise, there are duplicates.
Example 5: Finding Common Elements Between Two Arrays
Sets can be used to find common elements between two arrays efficiently.
const array1 = [1, 2, 3, 4, 5];
const array2 = [4, 5, 6, 7, 8];
const set1 = new Set(array1);
const commonElements = array2.filter((item) => set1.has(item));
console.log(commonElements);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[4, 5]
In this code:
1. We create a Set `set1` from the first array `array1`.
2. We use the `filter()` method on the second array `array2` to check if each element exists in `set1` using the `has()` method.
3. The result is an array `commonElements` containing the common elements between the two arrays.
Example 6: Storing Unique Objects in a Set
While Sets are great for storing primitive values, they can also store objects. However, objects are compared by reference, not by value.
const obj1 = { name: 'Alice' };
const obj2 = { name: 'Alice' };
const objectSet = new Set();
objectSet.add(obj1);
objectSet.add(obj2);
console.log(objectSet.size);

You can also try this code with Online Javascript Compiler
Run Code
Output:
2
In this code:
1. We create two objects `obj1` & `obj2` with the same properties.
2. We add both objects to a Set `objectSet`.
3. Even though the objects have the same content, they are considered different because they are stored as separate references.
4. The `size` of the Set is `2`, indicating both objects are stored.
How to Check for a Subset?
A subset is a Set that contains only elements found in another Set. To check if one Set is a subset of another, you can loop through all the elements of the first Set and check if they exist in the second Set.
Example
function isSubset(setA, setB) {
for (let elem of setA) {
if (!setB.has(elem)) {
return false;
}
}
return true;
}
let set1 = new Set([1, 2, 3]);
let set2 = new Set([1, 2, 3, 4, 5]);
console.log(isSubset(set1, set2));

You can also try this code with Online Javascript Compiler
Run Code
Output
true
How to Find Union?
The union of two Sets is a Set that contains all the elements from both Sets without duplicates. You can achieve this by adding all elements from both Sets into a new Set.
Example
function union(setA, setB) {
let result = new Set(setA);
for (let elem of setB) {
result.add(elem);
}
return result;
}
let set1 = new Set([1, 2, 3]);
let set2 = new Set([3, 4, 5]);
console.log(union(set1, set2));

You can also try this code with Online Javascript Compiler
Run Code
Output
Set { 1, 2, 3, 4, 5 }
How to Find Intersection?
The intersection of two Sets contains only the elements that are common to both Sets. You can find the intersection by checking if each element of one Set exists in the other.
Example
function intersection(setA, setB) {
let result = new Set();
for (let elem of setA) {
if (setB.has(elem)) {
result.add(elem);
}
}
return result;
}
let set1 = new Set([1, 2, 3]);
let set2 = new Set([2, 3, 4]);
console.log(intersection(set1, set2));

You can also try this code with Online Javascript Compiler
Run Code
Output
Set { 2, 3 }
How to Find the Difference of Two Sets?
The difference between two Sets includes elements that are in the first Set but not in the second. You can achieve this by checking which elements of one Set do not exist in the other Set.
Example
function difference(setA, setB) {
let result = new Set();
for (let elem of setA) {
if (!setB.has(elem)) {
result.add(elem);
}
}
return result;
}
let set1 = new Set([1, 2, 3]);
let set2 = new Set([3, 4, 5]);
console.log(difference(set1, set2));

You can also try this code with Online Javascript Compiler
Run Code
Output
Set { 1, 2 }
DSA Problems on Set
Finding Unique Elements in an Array: You can use a Set to easily find the unique elements in an array by converting the array to a Set.
let array = [1, 2, 3, 4, 4, 5, 5];
let uniqueElements = new Set(array);
console.log(uniqueElements);

You can also try this code with Online Javascript Compiler
Run Code
Output
Set { 1, 2, 3, 4, 5 }
Checking for Duplicate Values: You can also use a Set to check for duplicates while iterating over an array. If an element already exists in the Set, you know it's a duplicate.
function hasDuplicates(arr) {
let set = new Set();
for (let value of arr) {
if (set.has(value)) {
return true;
}
set.add(value);
}
return false;
}
console.log(hasDuplicates([1, 2, 3, 4, 5]));
console.log(hasDuplicates([1, 2, 3, 3, 5]));

You can also try this code with Online Javascript Compiler
Run Code
Output
false
true
Static Properties
In JavaScript, the Set object itself doesn’t have static properties. Static properties are properties that belong to the class itself rather than instances of the class. However, the `Set` object has a built-in constructor called `Set`, which is used to create new Set instances.
For example, to create a new Set, you use the `Set` constructor like this:
const mySet = new Set();
console.log(mySet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(0) {}
Here, `Set` is the constructor, & `mySet` is an instance of the Set object. The `Set` constructor can also take an iterable (like an array) as an argument to initialize the Set with values.
const numbers = new Set([1, 2, 3, 4, 5]);
console.log(numbers);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(5) {1, 2, 3, 4, 5}
In this example, the Set `numbers` is initialized with the values `[1, 2, 3, 4, 5]`. Since Sets only store unique values, if you try to add duplicate values, they’ll be ignored.
const duplicates = new Set([1, 2, 2, 3, 3, 4]);
console.log(duplicates);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(4) {1, 2, 3, 4}
Here, the duplicate values `2` & `3` are ignored, & the Set only stores unique values.
While the `Set` object doesn’t have static properties, understanding its constructor is crucial because it’s the foundation for creating & working with Sets in JavaScript.
Instance Properties
Instance properties are properties that belong to individual instances of the `Set` object. These properties provide information about the specific Set instance. The most commonly used instance property in a Set is `size`.
1. `size` Property
The `size` property returns the number of unique elements in a Set. It’s similar to the `length` property of an array but specifically for Sets.
For example:
const fruits = new Set(['apple', 'banana', 'orange']);
console.log(fruits.size);

You can also try this code with Online Javascript Compiler
Run Code
Output:
3
In this example, the Set `fruits` contains three unique elements: `'apple'`, `'banana'`, & `'orange'`. The `size` property returns `3`, indicating the number of elements in the Set.
If you add a duplicate value to the Set, the `size` property won’t change because Sets only store unique values.
fruits.add('apple'); // Adding a duplicate value
console.log(fruits.size);

You can also try this code with Online Javascript Compiler
Run Code
Output:
3 (size remains the same)
Here, even though we tried to add `'apple'` again, the `size` property remains `3` because `'apple'` was already in the Set.
2. Checking if a Value Exists in a Set
While not a property, the `has()` method is often used alongside instance properties to check if a specific value exists in the Set.
console.log(fruits.has('banana'));
console.log(fruits.has('grape'));

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
false
In this example, `fruits.has('banana')` returns `true` because `'banana'` is in the Set, while `fruits.has('grape')` returns `false` because `'grape'` is not in the Set.
Instance Methods
Instance methods are functions that belong to individual instances of the `Set` object. These methods allow you to manipulate & interact with the Set. Let’s discuss the most commonly used instance methods in detail.
1. `add()` Method
The `add()` method is used to insert a new element into the Set. If the element already exists, it won’t be added again because Sets only store unique values.
For example:
const colors = new Set();
colors.add('red');
colors.add('green');
colors.add('blue');
console.log(colors);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(3) {'red', 'green', 'blue'}
In this example, we created an empty Set `colors` & added three unique values: `'red'`, `'green'`, & `'blue'`. If we try to add a duplicate value, it will be ignored.
colors.add('red'); // Adding a duplicate value
console.log(colors);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(3) {'red', 'green', 'blue'}
Here, `'red'` is not added again because it already exists in the Set.
2. `delete()` Method
The `delete()` method removes a specific element from the Set. It returns `true` if the element was successfully deleted & `false` if the element doesn’t exist in the Set.
console.log(colors.delete('green'));
console.log(colors);

You can also try this code with Online Javascript Compiler
Run Code
Output:
true
Set(2) {'red', 'blue'}
In this example, `'green'` is removed from the Set, & the `delete()` method returns `true`. If we try to delete an element that doesn’t exist, it returns `false`.
console.log(colors.delete('yellow'));

You can also try this code with Online Javascript Compiler
Run Code
Output:
false
3. `clear()` Method
The `clear()` method removes all elements from the Set, making it empty.
colors.clear();
console.log(colors);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Set(0) {}
Here, the `clear()` method removes all elements from the `colors` Set, leaving it empty.
4. `forEach()` Method
The `forEach()` method allows you to execute a function for each element in the Set. It’s similar to the `forEach()` method for arrays.
const numbers = new Set([1, 2, 3]);
numbers.forEach((value) => {
console.log(value);
});

You can also try this code with Online Javascript Compiler
Run Code
Output:
1
2
3
In this example, the `forEach()` method iterates over each element in the `numbers` Set & logs it to the console.
5. `entries()` Method
The `entries()` method returns an iterator object that contains an array of `[value, value]` for each element in the Set. This is useful when you need both the key & value (which are the same in a Set).
const letters = new Set(['a', 'b', 'c']);
const iterator = letters.entries();
for (const entry of iterator) {
console.log(entry);
}

You can also try this code with Online Javascript Compiler
Run Code
Output:
['a', 'a']
['b', 'b']
['c', 'c']
Here, the `entries()` method returns an iterator where each entry is an array with the value repeated twice.
Frequently Asked Questions
What is a Set in JavaScript?
A Set is a collection of unique values in JavaScript. It stores values of any type (primitive or objects) without duplicates.
How do you add elements to a Set in JavaScript?
You can use the add() method to add elements to a Set. Example: mySet.add(1).
How can you find the union of two Sets?
You can find the union by adding elements from both Sets into a new Set. Example: union(setA, setB).
Conclusion
In this article, we discussed JavaScript Sets, including their creation, methods, and properties. We also demonstrated how to perform operations like checking for subsets, finding unions, intersections, and differences. Additionally, we looked at some common DSA problems related to Sets.
You can also check out our other blogs on Code360.