Sets in JavaScript
I was getting to know a code base Iβll be working with a lot more in my new role as a development engineer at Points the other week, and I came across something Iβd never seen before, a Set
. I initially thought it might be part of lodash or something similar, but no. It is a global object in Javascript, and I didnβt know anything about it!
Sets are similar to Arrays but with a main difference, a value in a set, be that a primitive or object ref, can only occur once it in itβs set (I like to think of it as an array that ignores duplicate insertions). Take this as a basic example:
You can use the usual suspects when it comes to iteration methods too:
This has been part of the spec for years and has very solid browser support. You can read more on the Set
object, and a really comprehensive set of examples on the MDN Docs.