JavaScript Sets: A Beginner's Guide

10 Feb 2024
10 minute read
The JavaScript Set is an object that comes built-in with the language and provides the ability to store values of any type, including primitive values or object references, to ensure uniqueness.

Javascript Set is implemented using a hash table data structure. When you add a new value to a Set using the add() method, the value is hashed and used as the key in the hash table. The actual value is stored as the value associated with that key.

When you check if a value is in the Set using the has() method, the value is hashed and looked up in the hash table. If the key is found, it means the value is in the Set, and the has() method returns true.

This hash table implementation makes adding and checking for values in a Set very fast, with a time complexity of O(1) on average. This means that adding or checking for values takes the same amount of time, regardless of the size of the Set.

Additionally, because a Set only allows unique values, the hash table implementation ensures that only one copy of each value is stored, which helps to conserve memory.

Performance

On Average sets are faster then array in many cases i.e. to determine the value exists in a set using has method is faster then Array.prototype.includes

Set is very usefull in many real world scenarios such as:

  • Removing duplicates from an array
  • Checking whether a value exists in a collection
  • Keeping track of visited items in an algorithm

Removing duplicates from an array

By creating a Set from an array, all duplicates will be automatically removed. You can then convert Set back to an array using the spread operator or the `Array.from()`` method.

In below example, we have an array of city names that contains some duplicates. We create a new Set uniqueCities from the array, which removes the duplicates since Sets can only contain unique values.

const cities = ['New York', 'Paris', 'London', 'New York', 'Tokyo', 'Paris'];
const uniqueCities = new Set(cities);
const uniqueCityArray = [...uniqueCities]; // ['New York', 'Paris', 'London', 'Tokyo']

We used the spread operator to convert the ‘uniqueCities’ set into an array, you can also use the Array.from method.

Checking whether a value exists in a collection

Instead of iterating over each element of an array to see if a value exists, you can use a Set to quickly determine whether or not a value exists.

const fruits = new Set(['apple', 'banana', 'orange']);
const hasBanana = fruits.has('banana'); // true
const hasGrape = fruits.has('grape'); // false

Keeping track of visited items in an algorithm

Suppose you’re implementing an algorithm that requires you to keep track of previously visited items, you can use a Set to store the visited items and quickly check if an item has already been visited.

const visitedItems = new Set();
function visitItem(item) {
  if (!visitedItems.has(item)) {
    visitedItems.add(item);
    // Do something with the item
  }
}