How to make your code faster using JavaScript Sets

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

Bret Cameron
6 min readMar 30, 2019

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…

--

--

Bret Cameron

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