You can create a set in ES6 by passing an array into the constructor:
1 2 3
Notice the array I passed in contains duplicates. But the set essentially strips them out and I’m left with a collection of 6 unique items (instead of the original 9 with duplicates), which is much more useful in certain situations.
You don’t have to pass in an array to create a set, but that’s one way to do it. You also have access to the
add() method, so you can do this:
1 2 3 4 5 6
Finally, there’s the
has() method, which is probably what you’ll use the most. This method allows you to check if an item exists. And because sets can’t contain duplicates, it’s a simple check, then you can move on to other things without any complexities:
1 2 3
The feature has strong browser support, so goahead and use this in your project.
Credits: MDN, WebWeekly Newsletter