DEV Community


Javascript ES6: Set

jeanetterosario profile image Jeanette Rosario ・2 min read

One of the additions brought on by Javascript ES6 is the Set data type. Set allows us to create a collection of unique* values. The values themselves can be of any data type, from primitive types like numbers, to reference types, like arrays.

Let's look at the simplest way to create and add values to a Set data type using the add method.

Alt Text

Above, we initialized a new Set named letters. And later on, we added values, in this case, strings, with the add method. What's important to note is that Sets only collect unique* values. Therefore, although we continued attempting to add more c's, the Set did not add those extra c's because it already had one.

Besides add, there are some simple, yet useful, methods we can use with Set: size, has, forEach, clear, delete.

We can also initialize a new Set and pass in an iterable object such as an array.

Alt Text

Above, we initialized a new Set with an array of strings: ['b', 'a', 'c']. That array was iterated over and deconstructed. Note how when we later add an array to the Set using the add method, in this case, ['f', 'e', 'h'], the array stays intact.

Here are few things to remember when using Set:
1) Strings are a valid iterable so they can initialize a set. However, remember the Set will only hold the unique* values in that string.
Alt Text
2) Set also has a keys and a values method. But they will produce the same result: the values of the Set.
Alt Text

3) Lastly, aside from forEach we can use a for...loop to iterate over a Set.
Alt Text

Discussion (0)

Editor guide