How to make your code faster using JavaScript Sets

If you only use arrays, you’re missing a trick

Bret Cameron

--

I’m sure there are plenty of developers who stick to the basic global objects: numbers, strings, objects, arrays and booleans.

For many use-cases, these are all you need. But if you want to make your code as fast and scalable as possible, these basic types aren’t always good enough.

In this article, we’ll talk about how JavaScript’s Sets can make your code faster — especially as it scales. There is a significant amount of crossover between what an array can do and what a Set can do. But using Sets will often bring runtime benefits that are impossible to achieve with arrays. In this article, we’ll explore how.

How are Sets different?

The most fundamental difference is that arrays are an indexed collection. That means the value of data in an array is ordered by the index.

const arr = [A, B, C, D];console.log(arr.indexOf(A)); // Result: 0
console.log(arr.indexOf(C)); // Result: 2

By contrast, Sets are a keyed collection. Instead of using indices, Sets order their data using keys. A Set’s elements are iterable in the order of insertion, and it cannot contain any duplicate data. In other words, every item in a Set must be unique.

What are the main benefits?

In a direct comparison, Sets have several advantages over arrays, especially when it comes to a faster run-time:

  • Search for an Item: Using indexOf() or includes() to check whether an item exists in an array is slow.
  • Deleting an Item: In a Set, you can delete an item by its value. In an array, the equivalent is using splice() based on an element’s index. As in the previous point, depending on indices is slow.
  • Insert an Item: It is faster to add an item to a Set than to add an item to an array using push() , unshift() or an equivalent method.
  • Storing NaN: You cannot use indexOf() or includes() to find the value NaN , while a Set is able to store this value.
  • Removing Duplicates: Set objects only store unique values. If you want to…

--

--

Bret Cameron

Writer and developer based in London. On Medium, I write about JavaScript and web development 💻