Sets are an object type that let you create a collection of values that must be unique. This is useful in cases when you are faced with potential duplicates, but only want to store a single instance of that value. Any duplicates are ignored.

Sets are like these buckets: they're unique.

Creating a Set

Creating a set, like creating any object is extremely simple in JavaScript.

JAVASCRIPT
const set = new Set();

That's it, you're now ready to add elements to your set.

Add

Once you have created your set, adding elements to it is similar to adding elements to an array. Simply call the add method on your set with the element you want to add. The element will be added to the set.

JAVASCRIPT
const set = new Set(); set.add("Facebook"); set.add("Twitter"); set.add("LinkedIn"); console.log(set);
JAVASCRIPT
{"Facebook", "Twitter", "LinkedIn"}

Great, you added elements to your set, but watch what happens if you try adding Facebook twice.

JAVASCRIPT
const set = new Set(); set.add("Facebook"); set.add("Twitter"); set.add("LinkedIn"); set.add("Facebook"); // duplicate console.log(set);
JAVASCRIPT
{"Facebook", "Twitter", "LinkedIn"}

Just as expected, the second Facebook was ignored because it already existed in the set, and therefore was a duplicate.

Size

Sets give you a very straight-forward way to get back the size of your set. Simply use the size property.

Using the same scenario above:

JAVASCRIPT
const set = new Set(); set.add("Facebook"); set.add("Twitter"); set.add("LinkedIn"); set.add("Facebook"); // duplicate console.log(set.size);
JAVASCRIPT
3

Our set only contains 3 elements despite having added four elements because one was a duplicate.

Has

When you want to check if a set contains an element, call the has method on it. This method will return true if the element is in the set, and false if it's not.

JAVASCRIPT
const set = new Set(); set.add("Cake"); set.add("Muffin"); set.add("Donut"); console.log(set.has("Donut")); console.log(set.has("Cookie"));
JAVASCRIPT
true false

Delete

Deleting an element from a set is as simple as calling the delete method, and passing in the element you want removed. This will return true if the element was deleted, and false if it wasn't.

JAVASCRIPT
const set = new Set(); set.add("Cake"); set.add("Muffin"); set.add("Donut"); console.log(set); set.delete("Cake"); console.log(set);
JAVASCRIPT
{"Cake", "Muffin", "Donut"} {"Muffin", "Donut"}

Clear

To wipe a set clean of all of its elements, call the clear method on it. It resets a set as if you had just created a new one. This is useful if you want to start fresh.

JAVASCRIPT
const set = new Set(); set.add("Cake"); set.add("Muffin"); set.add("Donut"); set.clear(); // RIP elements console.log(set);
JAVASCRIPT
{}

Resources

Next Lesson »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.