Member-only story

The Underused Power of JavaScript Sets

Unlocking Unique Value Handling

Max N
2 min readFeb 21, 2024

Working with unique values is common in programming. You may need to remove duplicates from an array, check if a value already exists, or operate on a collection of unique items.

JavaScript has a built-in Set object that handles unique values elegantly, yet it often gets overlooked. In this post let’s explore some great ways to put JavaScript Sets to work!

Creating JavaScript Sets

A Set can be initialized from any iterable object, like an array:

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

Notice duplicates are automatically removed! We can also create an empty set:

const ids = new Set();

And insert values with .add():

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

Checking Existence

A key use of sets is quickly checking value existence. The .has() method checks for membership:

ids.has(2);
// true

This provides O(1) lookups versus O(N) searching arrays!

Deleting & Clearing

--

--

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