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:

  • 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()

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

.has()

one.has("Hello")
//true

.size()

one.size()
//1

.forEach()

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

.delete()

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

.clear()

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

Software Developer — Game Creator — Let’s work together! Reach out on LinkedIn or Twitter @thedrewprint

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store