Set

We'll cover the following...

In the previous chapter we looked at the Map object, and how we can use it to store key/value pairs. In this chapter we will look at Set and how to store unique values.

A Set is created in the same way as Map.

Press + to interact
const shoppingList = new Set();

add()

With a Set we can use the .add() method to add elements to the Set. This is where a Map and Set differ: there are no keys in a Set.

Press + to interact
shoppingList.add('Milk');
shoppingList.add('Cheese');

Adding multiple values

When we create a new Set we can pass in an array of values for our Set.

Press + to interact
const shoppingList = new Set(['Milk','Cheese']);

has()

The .has method can be used to check if a value exists in the Set. ...