JavaScript Introducing ES2015 Objects and New Collection Types Set

Why use Set at all?

What are the advantages of using Set instead of just using arrays or objects? I can't seem to find any real-world examples of how using Set is a better option...

3 Answers

Christian Andersson
Christian Andersson
8,508 Points

One of the biggest differences of a Set is that it only allows unique values - you cannot have duplicates - which can be an advantage in certain cases.

Sets also have convenient methods, such as has() to find out if an element exists or not. It is also an iterable object which can help iterate over the element in the object.

There are other objects that are more common and offer similar features, such as Map. The Set specifically has the benefit of the unique-elements requirement, which would save the headache of checking-before-inserting that you would otherwise have to do with, say, Arrays.

If you don't need this requirement, I would suggest using a Map or some other Object - perhaps even a simple Array.

Gotcha, thank you!

Greg Schudel
Greg Schudel
4,090 Points

The Set specifically has the benefit of the unique-elements requirement, which would save the headache of checking->before-inserting that you would otherwise have to do with, say, Arrays.

what is checking-before-inserting? you mean running a console.log check to see what the interpreter is actually processing? Can you provide an example of what you mean please?

Tom Geraghty
Tom Geraghty
24,147 Points

There are many cases where you wouldn't want data to be duplicated in a list. If you're dealing with a Set of Users who are authorized to use your website. You would want each user to be unique, right?

Another example would be wanting to compare two sets for any intersection (i.e.: both sets contain the same unique content). That could be information used to drive your business, etc.

This might give you some things to think about: https://www.khanacademy.org/math/statistics-probability/probability-library#basic-set-ops