Learn the Incredibly Helpful but Often Overlooked JavaScript Built-In Set Object
Tags: javascript, webdev, node, react
Published: 2020-06-16 12:32:07

---
title: Learn the Incredibly Helpful but Often Overlooked JavaScript Built-In Set Object
published: true
description: Set is one of my favorite built-in object types in JavaScript. Today I'll introduce the `Set` object and discuss some of its use cases.
tags: javascript, webdev, node, react
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/c4jymg5axbwjrktsq7wk.png
canonical_url: https://typeofnan.dev/the-javascript-set-object/
---

Please give this post a 💓, 🦄, or 🔖 if you learned something!

`Set` is one of my favorite built-in object types in JavaScript. Today I'll introduce the `Set` object and discuss some of its use cases.

## Video Tutorial

I made a video version of this tutorial! Check out this YouTube video if you prefer learning that way.

{% youtube wxJrmT-UR4s %}

# The Set Object

The `Set` object is a collection of values in which you can store **unique** primitive values or object references. Uniqueness is key here--no primitive value or object reference will can added multiple times.

## How to Use Set

To use set, you create a new instance of it.

```javascript
const mySet = new Set();
```

We now have an empty set. We can add the number `1` to this set by using the `add` method.

```javascript
mySet.add(1);
```

How do we know that we've added `1`? We can use the `has` method to check.

```javascript
console.log(mySet.has(1));
// true
```

Let's add an object reference now and then check that we have that object in our `Set`.

```javascript
const obj = { name: 'Daffodil' };
mySet.add(obj);
console.log(mySet.has(obj));
// true
```

Remember that object references are compared, not the object keys themselves. In other words:

```javascript
console.log(mySet.has({ name: 'Daffodil' }));
// false
```

We can see how many elements are in the `Set` by using the `size` property.

```javascript
console.log(mySet.size);
// 2
```

Next up, let's remove a value using the `delete` method.

```javascript
mySet.delete(1);
console.log(mySet.has(1));
// false
```

Finally, we'll clear out the `Set` using the `clear` method.

```javascript
mySet.clear();
console.log(mySet.size);
// 0
```

## Iterating Over a Set

The easiest way to iterate over a `Set` is to use the `forEach` method.

```javascript
new Set([1, 2, 3]).forEach(el => {
  console.log(el * 2);
});
// 2 4 6
```

`Set` objects also have `entries`, `keys`, and `values` methods, which each returns [Iterators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). Those are a bit outside the scope of this tutorial!

## Using Sets in the Wild

I find the `Set` object to be really great for keeping track of a _binary state_ associated with an object. A great example is an accordion menu: each item in the menu will either be open or closed. We can create a `Set` called `isOpen` that tracks the open status of an accordion item and a `toggle` function that toggles the open status:

```javascript
const isOpen = new Set();

function toggle(menuItem) {
  if (isOpen.has(menuItem)) {
    isOpen.delete(menuItem);
  } else {
    isOpen.add(menuItem);
  }
}
```

## A Note of Efficiency

You might be thinking that the `Set` object seems awfully similar to arrays. There is, however, a big difference that may have performance ramifications in your application. The `Set` object is required to be implemented using hash tables (or methods with hash table-like efficiency) [1].

When you store something in an array, you might have to traverse the entire array to find the item. With a `Set`, however, the lookup is instantaneous. Practically speaking, the performance will be negligable for _most_ cases, but good to remember if you find yourself having to track large numbers of items!

# Conclusion

I hope this helped you understand the `Set` object and you now have a new tool in your JavaScript toolbelt!

---

References

1. [Set Object Specification](http://tc39.es/ecma262/#sec-set-objects)