Sets: The Unique Values Collection

Sets: The Unique Values Collection
Table of Contents
  1. Creating a Set
  2. Add
  3. Size
  4. Has
  5. Delete
  6. Clear
namecheap placeholder image

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.
Sets are like these buckets: they're unique.

Creating a Set

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

	
    var 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.

	
    var set = new Set();

    set.add("Facebook");
    set.add("Twitter");
    set.add("LinkedIn");

    console.log(set);
	
	
    {"Facebook", "Twitter", "LinkedIn"}
	

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

	
    var set = new Set();

    set.add("Facebook");
    set.add("Twitter");
    set.add("LinkedIn");
    set.add("Facebook"); // duplicate

    console.log(set);
	
	
    {"Facebook", "Twitter", "LinkedIn"}
	

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

udemy placeholder image

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:

	
    var set = new Set();

    set.add("Facebook");
    set.add("Twitter");
    set.add("LinkedIn");
    set.add("Facebook"); // duplicate

    console.log(set.size);
	
	
    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.

	
    var set = new Set();

    set.add("Cake");
    set.add("Muffin");
    set.add("Donut");

    console.log(set.has("Donut"));
    console.log(set.has("Cookie"));
	
	
    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.

	
    var set = new Set();

    set.add("Cake");
    set.add("Muffin");
    set.add("Donut");

    console.log(set);

    set.delete("Cake");

    console.log(set);
	
	
    {"Cake", "Muffin", "Donut"}
    {"Muffin", "Donut"}
	
bluehost placeholder image

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.

	
    var set = new Set();

    set.add("Cake");
    set.add("Muffin");
    set.add("Donut");

    set.clear(); // RIP elements

    console.log(set);
	
	
    {}