Sets

Learn how to use sets, a data structure just introduced to JavaScript.

We'll cover the following...

Introduction

Sets are a data structure commonly used in computer science.

A set is a collection of values. Think of it like a bucket. A set provides easy ways to insert and remove items. We can easily check if an item is present in our set and we can get all items back in a way that makes them easy to use.

Creating a Set

We invoke a set using:

new Set();

Inside the constructor call, we can pass in an iterable object, usually an array. Every item in the array will be inserted into the set.

Press + to interact
const set = new Set(['abc', 'def', 'ghi']);
console.log(set); // -> Set { 'abc', 'def', 'ghi' }

new Set('string');

One important caveat is that a string is also considered an iterable. If we call new Set() with a string, each individual character will be inserted into the set.

Press + to interact
const set = new Set('abcde');
console.log(set); // -> Set { 'a', 'b', 'c', 'd', 'e' }

It’s a common mistake to pass multiple arguments into the set constructor. This will not work. The set constructor takes zero or one arguments. All others will be ignored. The only way to pass in multiple items is ...