DEV Community

Steven Frasica
Steven Frasica

Posted on

Learn About JavaScript Sets

Sets were introduced in the ES6 update to JavaScript.
Sets in JavaScript are a data type which I've recently learned about and became interested in learning more about its uses. A set is a collection of unique values. Unlike an array, it cannot contain duplicate values. Sets can hold primitive data types and objects.

Creating a Set

You can create an empty set using a constructor like so -

const firstSet = new Set()

A new set can also be created out of an array, or an iterable. An iterable is something that can be looped through, and in this case we're using an array. Strings are also iterable.

const secondSet = new Set([1, 2, 3, 4, 5, 5])

The array used to create secondSet has duplicates of 5. Let's log secondSet to the console and set what we get.

console.log(secondSet)
//Output will be Set {1, 2, 3, 4, 5}

As you can see, secondSet only has one value of 5, despite being passed in an array with duplicate values.
If you ever only want the unique values in an array, pass it in as an argument when creating a new set.

.add() Method

Use the .add() method to add new, unique values to a set. The .add() method will return the set containing the new value.

const colorSet = new Set()

colorSet.add('red')
//returns Set {"red"}

The .add() method can also be chained to other methods including itself.

colorSet.add('blue')
        .add('yellow')
        .add('green')

//returns Set {"red", "blue", "yellow", "green"}

.has() Method

The .has() method will return a boolean dependent upon whether or not the element passed in exists as a value in a set.

colorSet.has('blue')
//returns true

colorSet.has('orange')
//returns false

.delete() Method

The .delete() method will remove a specified element from the set and return a boolean dependent upon if the element was successfully removed. Our colorSet currently has 'green' in it. We'll remove it from colorSet so it only contains primary colors.

colorSet.delete('green')
//returns true

If the .delete() method is unsuccessful, it will return false.

colorSet.delete('orange')
//returns false

There was no 'orange' value in the colorSet, which is why .delete() returned false.

Create an Array from a Set

We went over how to create a set from an array, but it is also possible to create an array from a set using the Array.from() method.

const colorArray = Array.from(colorSet)

console.log(colorArray)
//Output is ["red", "blue", "yellow"]

There is much more to the set datatype. Read up on the documentation here.

Check out these links as well.

-Set tutorial
-Set vs Array
-Another article on set vs array

Top comments (0)