Lesson 24. Sets
After reading lesson 24, you will
- Know how to use and create sets
- Know how to perform array operations on sets
- Understand when to use arrays and when to use sets
- Understand what WeakSets are and when to use them
Sets are a new type of object in JavaScript. A set is a unique collection of data. It can store any data type but won’t store duplicate references to the same value. Sets are iterables, so you can use spread and for..of with them. Sets are most closely related to arrays; however, when you use an array your focus is generally on the individual items in the array. When dealing with a set, you’re usually dealing with the set as a whole.
Consider this
Imagine you’re building a video game where the player starts with a set of skills and as the player encounters new skills, they’re added to the player’s skill set. How would you make sure that the player never ends up with duplicate skills?
There’s no literal version of a Set, such as [ ... ] for arrays or { ... } for objects, so sets must be created using the new keyword like so:
Additionally, if you want to create a set with some initial values, you can use an iterable as the first (and only) parameter:
Now this set will have three strings as initial values. Whenever you use an iterable as the parameter, the iterable’s individual values get added as items in the set, not the iterable itself: