30 Days Of JavaScript

Day 2: Collection Types

Lesson 2: Sets

Sets are like arrays with one key difference. Every item in a set must be unique.

So, [1,2,3,4,4,4] is a valid array but would not be a valid set. In fact the way that sets are made and worked with in JavaScript means that it's impossible for you to create a set that breaks this rule.

A few things to note here:

  1. When we created the set we used an array to seed it, since it's the same array as above we could simply have done let agesAgain = new Set(ages); (hint: change the playground now and see for yourself).

  2. We create a set in a different way with the new Set() syntax. new is a keyword in JavaScript and it is always followed by something called a constructor, in this case Set().

  3. When logging out the agesAgain it looks different in the terminal, it shows with curly braces { } and you need to expand it, unlike your array on the line above.

Now, I'm going to let you in on a fun use of these two data types waaaaay earlier than you would usually come across it. Removing duplicates is a common, and annoying, task. Well, if I tell you the you can create a set from an array, and that you can create an array from a set ... Then you can use these to deduplicate an array into two lines of code. Let's take a look:

If sets are deduped then why bother going back to the array you might wonder? Well Sets are a little trickier to work wih than arrays and most of the time, with the exception of this trick, you'll be using arrays. This is such a useful trick though I wanted to show you it here.

More on arrays later. Let's look at objects next.

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co