Sets in Javascript

Andrew Richards
2 min readSep 9, 2020

--

Set’s are a new type of Javascript object that was introduced in ES6 to take care of a multitude of issues that could not be taken care of with a normal Javascript or Array. The primary focus being only storing unique values.

Get it, because you set a table…

Unlike and Object or Map, Sets function a bit more like arrays. For example, there are no key value pairs in a set.

A great use case for a Set is when you want to create an array with only unique values. You could do this with an array but you have to check every single value you add to the array against itself, which will be costly. Sets on the other hand have this functionality built in.

Great things about Sets:

  • A Set is not a good thing to use when you can have multiple of the same value.
  • Sets can also store more than just values. They can store objects or arrays as well.

Let’s create a set and see some of the methods we can use with it.

let one = new Set()
let two = new Set("Hello")
console.log(two)
//Set { "H", "e", "l", "o"})

Interestingly, when creating a new set and passing a string in on initialization, it will break it up into each character. Which is great if you’re trying to find every unique letter in a string.

You can also pass an array in and it will take each value separately.

.add()

Add will simply add a value to the set. If the value already exists in the set, it will not get added.

one.add("Hello")
console.log(one)
//Set {"Hello"}

.has()

Returns a boolean if the set has the value.

one.has("Hello")
//true

.size()

Returns the size of the set.

one.size()
//1

.forEach()

You can iterate through the set in the order of entry.

one.add("Hi")
one.add("Hello")
one.add("Ham Sandwich")
one.forEach(value => {
console.log(value)
})
//"Hi"
//"Hello"
//"Ham Sandwich"

.delete()

You can delete specific values in the Set by passing them as a parameter in the delete method.

one.delete("Hi")// removes "Hi" from the set.

.clear()

You can entirely clear out a set with one simple method.

one.clear()// clears out the entire set
// Set {}

That just about does it. If you would like to dig a bit deeper into sets, click on the link below.

Thank you for reading. Please follow me on twitter @thedrewprint and find me on LinkedIn — Andrew Richards

--

--