Monday, October 19, 2015

JavaScript Collections - Set

In addition to Map, JavaScript also got another popular collection type this year - the Set. As part of ECMAScript 2015, which is now mostly supported by Node.js, this new build-in object type was added to the language. It's also available on the client-side in Firefox, but it's probably best to keep it on the server side for right now.

So how does it work? Pretty much like you'd expect a Set to work. You can add values to it, but it can only hold unique values (contrast this with Array, which can hold multiple of the same object).

As you can see from the example, it supports the standard functions for adding, removing, and checking. Note that, just like Map, the type of objects that can be put in a Set are wide open. You can keep Strings, Numbers, Booleans, and even Functions in the same set. The Booleans are interesting - look at line 5 above. You can add false to the Set. Then s.has(false) returns true. But the fun doesn't end there. You can even put Infinity (NaN) in the Set if you want. Why would you want to? I have no idea, but it works.

The iteration will produce the contents in insertion order, which is why the above example prints one, tree, and then two. There's not really a way to re-order the Set.

Just like I said about Maps, I haven't really been missing them from JavaScript. There's plenty of ways to get around their absence. But now that they're part of the language, I'm sure I'll end up using one somewhere. Personally, I think Sets add more to JavaScript than Maps do simply because of the unique item enforcement.