Member-only story

Using JavaScript Sets for Unique Values

Working with unique values

Max N
2 min readFeb 20, 2024
Photo by Noah Näf on Unsplash

Working with unique values is a common task in programming. JavaScript has a built-in Set object that makes managing unique values simple. In this post, we’ll explore using JavaScript Sets for unique value use cases.

Creating Sets

A Set can be initialized with any iterable object, like an array. Duplicates are automatically removed:

const ids = new Set([1, 2, 2, 3]); 
// ids = Set(3) {1, 2, 3}

We can add additional values using .add():

ids.add(4);
// ids = Set(4) {1, 2, 3, 4}

And check for existence with .has():

ids.has(2); 
// true

Removing Values

We can remove a value with .delete(), returning a boolean indicating whether the value existed:

ids.delete(3);
// true

ids.has(3);
// false

And clear out all values with .clear():

ids.clear(); 
// []

Iterating Sets

We can iterate over a set, such as to operate on each id:

for (let id of ids) {
console.log(id);
}

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet