ABOUT

What are JavaScript Sets?

What is a JavaScript Set?

Javascript Sets were introduced in 2015 with the release of ES6.

At first glance, they may seem like a hash or an array, but there are some major differences.

How does a JavaScript Set differ from an Array?

A Set can only contain unique values, each value can only occur once. A Set can hold any data type. Data stored in a set cannot be accessed by index.

Example:

const newData = mySet[2] //this would return undefined

How to declare JavaScript Sets.

To declare a Set you must use the ‘new’ keyword.

Example:

const mySet = new Set()

How to add data to a Set.

You can add data to a set by passing an array to it on initialization or using the .add() function.

Example of adding data to a Set.

const myArray = [1, 2, 3, 4]

const mySet = new Set(myArray)

console.log(mySet) // output {1, 2, 3, 4}

//additionally you can use the add() function

mySet.add(5)

console.log(mySet) // output {1, 2, 3, 4, 5}

JavaScript Set can not contain duplicate values.

If you add duplicate values to a Set they are deleted. This is a nice way to remove duplicate values from an Array.

Example:

let chars = ['A', 'B', 'A', 'C', 'B'];

let uniqueChars = [...new Set(chars)];

console.log(uniqueChars) // output [A, B, C]

Sets have some other really cool functions to explore.

delete() Removes an element from a Set

has() Returns true if a value exists

clear() Removes all elements from a Set

forEach() Invokes a callback for each element

values() Returns an Iterator with all the values in a Set

keys() Same as values()

entries() Returns an Iterator with the [value, value] pairs from a Set

Conclusion

In my opinion, Set is only useful for a handful of use cases where it outperforms Arrays. Such as when you want to store data and know you do not want duplicates.

You could write a function to check if an Array contains a piece of data before storing it, but it would be slower than a Set and add complication to your code.

It’s good to know these tricks though and they do often come up in projects.

If you have any questions email me aaron@xeleven.tech