Sets
Explore the concept of Sets in JavaScript as introduced in ES2015. Understand how to create Sets, add or remove items, and the unique property of storing only distinct values. Discover methods for checking presence, iterating over items, and converting Sets to arrays. This lesson helps you confidently use Sets to manage collections of data and understand their limitations in 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.
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.
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 ...