For more tips like this, sign up to the weekly newsletter!

Use a Set instead of an Array

Javascript Arrays are indexed structures, i.e., they store elements at indices. This behavior makes them highly versatile, where you have full control over both the data and the ordering.

But this versatility is not needed in many cases. In most real-world use-cases, we only need to know if something is in the collection or not, but we don't care where exactly.

For that, an Array is an overkill, and a Set is a better-suited structure.

For example, we have an Array of users:

const users = [
  "user1",
  "user2",
  "user3"
];

Let's create another structure for the active users!

Another Array is a trivial choice, but let's see if we can do better.

ES6 Sets

ES6 Sets are much simpler structures. An element is either in the Set or not.

As such, its API is built around this concept: you can add and remove elements, check if a particular one is present, and a few other helper functions. There are no indices, and it doesn't matter if an element is added multiple times.

As for the example above, to store the active users let's create a Set, add some users, and check if a particular one is active or not:

const activeUsers = new Set();

activeUsers.add("user1");
activeUsers.add("user3");

activeUsers.has("user1") // true
activeUsers.has("user2") // false
Simple structures

When a simpler data structure is enough for a particular use-case, prefer that. That enables significant optimizations, and also indicates the intention clearer.

Using a Set when its API is enough is one such optimization.

Try it
References
Learn more: