Intro to Sets in Javascript

Andrew Matheny
The Startup
Published in
3 min readMay 17, 2020

--

Photo by Sam McGhee on Unsplash

With the release of ES6 in 2015 Sets were introduced into Javascript. They are kind of like a hash or array but with some cool properties to use. I was recently working on an algorithm problem where Sets made it a lot easier to solve. I am going to go over the basics of a Set to get you started. I am going to use an example keeping track of crayons.

Initializing a new Set

From there you can things to the set either on initialization or after using the .add() function of Sets.

Initializing the Set with an array of colors
Adding a new item after initialization

What is really neat about .add() is it automatically checks for duplicates.

Despite adding yellow a second time it only shows up once but still adds green into the Set

You can also remove specific items from the set using .delete()

Removing green from the Set

If you want to clear out the Set you simply use the function .clear()

Very easy and straightforward

Alright so we have created a Set that can hold items in it and remove specific ones out, add more, or clear it out. Suppose we want to check if we have a specific crayon in our Set already.

.has() will return either true or false if the input matches an item in the Set.

We can also iterate through the set using forEach.

Also if you want to know the length of the set then .size can be used. Unfortunately .length like many of you are used to from arrays will find that using that will result in undefined.

You can even add in hashes or arrays into a set.

Alright so that was a quick overview of Sets. I hope it was helpful and obviously there is a lot more you can do with this. I will leave the docs below so that if you want more information about Sets you can check it out.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

--

--