Sets: Collections of Unique Values

Grade 13, page 8 of 12. A one-minute read.

A Set is a collection of values where every value is unique. No duplicates allowed. If you try to add something that's already there, nothing happens.

JavaScript
const visitors = new Set();

visitors.add("Mia");
visitors.add("Omar");
visitors.add("Mia");   // already there: ignored!
visitors.add("Zoe");

console.log(visitors);
console.log(visitors.size);
console.log(visitors.has("Omar"));
console.log(visitors.has("Sam"));

visitors.delete("Omar");
console.log(visitors);

It prints

Set(3) { 'Mia', 'Omar', 'Zoe' }
3
true
false
Set(2) { 'Mia', 'Zoe' }
Method / propertyWhat it does
set.add(value)Adds a value (if it's not already there)
set.has(value)true if the value is in the set
set.delete(value)Removes a value
set.sizeHow many values (note: size, not length!)

You can loop over a set with for...of, and turn it into an array with spread. This gives you the most famous one-liner in JavaScript, for removing duplicates from an array:

JavaScript
const votes = ["burger", "omelet", "burger", "pasta", "omelet", "burger"];
const uniqueDishes = [...new Set(votes)];
console.log(uniqueDishes);

It prints

[ 'burger', 'omelet', 'pasta' ]

Remember the "remove duplicates" homework from Grade 7? Yep. One line.

has is also much faster than array.includes when you have lots of items, which makes sets great for things like "have we already seen this?" checks.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning