WeakSets are one of the most undervalued keyed collections. A keyed collection is basically collections of data that are ordered by a key. I recently wrote an article about their sibling, WeakMaps.

For us to fully understand the beauty of WeakSets, we have to first learn about their bigger sibling — Sets. Let’s now learn what Sets are.

Set

In the above paragraph, I mentioned that WeakSets are a keyed collection. Similarly, Sets are a keyed collection too. Sets are analogous to Arrays in JavaScript with a few differences.

Now you might start to wonder, how can Sets be keyed while arrays are indexed. The reason is that you cannot access a value in a set by its index. This is because these values are arranged as key-value pairs. The reason why Sets do not allow duplicate values is that the keys are the same as the value. This would result in a duplicate entry causing no harm to the uniqueness of the values in the Set.

You can iterate the values in a Set by in the order of insertion by using the iterator. As I have explained above, a value in a Set may only occur once; it is unique in the Set’s collection.

Here are some of the differences between these two collections.

#javascript #web-development #nodejs

Understanding WeakSets in JavaScript
4.00 GEEK