Sets are a new object type introduced alongside a million other new features in ES2015. I don't use them all the time, but when I do, they make my life much easier!

<aside> <img src="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/7d8789f5-7cf0-4c73-bb6d-57397a7ad729/one.png" alt="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/7d8789f5-7cf0-4c73-bb6d-57397a7ad729/one.png" width="40px" /> The first thing you need to know is that Sets are collections of UNIQUE values. One more time: ALL VALUES IN A SET MUST BE UNIQUE.

</aside>

Sets often get lumped in with Arrays because they are both data collections, but there are some significant differences:

In general, Sets offer way fewer methods/features than Arrays. However, in the right situation Sets can be significantly faster and easier to use than Arrays.

Creating Sets

To make a new Set, we call new Set(). There is no Set literal/shortcut syntax ☹️

const hashTags = new Set();

This creates a new empty Set. When making a new Set, you can also pass in an iterable object. All the values in the iterable will be added to the new Set. For example:

const hashTags = new Set(["#selfie", "#nofilter"])

Results in a new Set which contains 2 entries:

▶ Set(2) {"#selfie", "#nofilter"}

<aside> <img src="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c462d0b8-a825-4d00-bea6-9e6fb7ad0a6d/problem.png" alt="https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c462d0b8-a825-4d00-bea6-9e6fb7ad0a6d/problem.png" width="40px" /> Note: You cannot pass a non-iterable to new Set() Something like new Set(1234) does not work! Neither does new Set(1,2,3,4). You have two choices: pass in an iterable object OR create an empty Set.

</aside>

Adding to Sets

Now that we've created a new Set, let's add some items. There is only a single method to add items to a set: add()

const annoyingHashTags = new Set();
annoyingHashTags.add("#YOLO");
annoyingHashTags.add("#Blessed")

Our set now looks like:

▶ Set(2) {"#YOLO", "#Blessed"}

If you try and add a duplicate value, it will be ignored: