JavaScript: Set

Bharath Kumar Murugan
2 min readApr 23, 2023

The Set data type is a collection of unique values. It allows you to store values of any data type, such as numbers, strings, booleans, objects, or even other Sets, but each value can only appear once within the Set. The order of the elements in a Set is maintained as they are inserted, and you can iterate over the elements in the same order.

Creating a Set To create a Set in JavaScript, you can use the Set() constructor or the new Set() syntax:

const mySet = new Set();
const mySet2 = new Set([1, 'hello', { key: 'value' }]);

In the first example, an empty Set is created. In the second example, a Set is created with three elements: a number, a string, and an object.

Adding and Removing Elements To add an element to a Set, you can use the add() method:

mySet.add(1);
mySet.add('hello');
mySet.add({ key: 'value' });

You can also add multiple elements at once using the spread operator:

mySet.add(...[1, 'hello', { key: 'value' }]);

To remove an element from a Set, you can use the delete() method:

mySet.delete('hello');

Checking if an Element Exists You can check if an element exists in a Set using the has() method:

mySet.has(1); // true
mySet.has('hello'); // false

Getting the Size of a Set You can get the size of a Set using the size property:

mySet.size; // 2

Iterating over a Set You can iterate over a Set using a for…of loop or the forEach() method:

for (const element of mySet) {
console.log(element);
}
mySet.forEach((element) => {
console.log(element);
});

Set Operations Sets have several built-in operations that allow you to perform common set operations, such as union, intersection, and difference.

Union

The union of two Sets contains all the unique elements from both Sets:

const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);

const union = new Set([...setA, ...setB]);

Intersection

The intersection of two Sets contains only the elements that are present in both Sets:

const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);

const intersection = new Set([...setA].filter(x => setB.has(x)));

Difference

The difference of two Sets contains only the elements that are present in the first Set but not in the second Set:

const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);

const difference = new Set([...setA].filter(x => !setB.has(x)));

Conclusion

In conclusion, the Set data type in JavaScript is a powerful tool for managing collections of unique values. With Sets, you can add and remove elements, check if an element exists, iterate over the elements, and perform set operations such as union, intersection, and difference. Understanding Sets can help you write more efficient and concise code in your JavaScript applications.

--

--

Bharath Kumar Murugan
0 Followers

FrontEnd Developer | Javascript Enthusiast | Linux | Docker