New Built-in Classes: Set
Learn about the basics of the new built-in class, sets of JavaScript.
Motivation to bring sets and maps in JavaScript
We often use collections of objects when programming. In other languages, you may have used arrays, lists, sets, associative maps, or dictionaries. Sadly, JavaScript offered only arrays in the past.
When programmers needed a set or a map in JavaScript, they resorted to workarounds. These workarounds made code hard to maintain, and when code resulted in unintended behavior, we had more errors to deal with.
Now, JavaScript offers built-in classes for sets and maps as first-class citizens in the language. We will take a look at sets first and then maps. We will wrap up by looking at some special variations of these two classes for better memory usage.
Using Set
The Array
class that has been available in JavaScript from the beginning is sufficient to deal with an ordered collection of data. However, what if you wanted to create an unordered collection? What if you needed values held in the collection to be unique? Say you want to keep a collection of credit cards that belong to a user. You may want to query whether a particular credit card exists in your collection. Array
is a poor choice for such operations; we really need a Set
. JavaScript has finally agreed with that sentiment.
Definition: A set is a unique collection of primitives and objects; duplicates are not allowed.
We can create an empty set and add objects to it or we can initialize a set with the contents of an iterable, like an array.
Sets in action
Here’s a set of names with five values, but one of the values presented during construction is not included in the set due to duplication.
Use the size
property to get the current number of elements in the set.
Get hands-on with 1400+ tech skills courses.