Sets are a new object type introduced in ES6 (ES2015). Although they are lesser known, they can be very useful and powerful. This tutorial will help you learn all you need to know about them. You will learn about what sets in JavaScript are, how they work and how to use them.

Introduction to sets

Sets are a new object type that was introduced to JavaScript with ES6 (ES2015). What sets allow you to do is to create collections of values. These values can be anything, from numbers and strings to arrays and objects. This doesn’t sound like something exciting. You can do the same thing with arrays.

The thing about sets, and where they differ from arrays, is that they can contain only unique values. When you try to add multiple same values into a set it will accept only the first. Any subsequent same value will be ignored. This also applies to values such as null and undefined. Each will be added only once.

This is one of the reasons why JavaScript developers sometimes choose sets over arrays. When you want to create a collection of some values, and you need all values to be unique, sets are the easiest option.

Creating sets in JavaScript

When you want to create sets in JavaScript you do it always with the set constructor set(), preceded by the new keyword. This will create new Set object.

// Create new empty set
const mySet = new Set()

Adding values to sets

When you are creating new set, there are two things you can do. First, you can create new empty Set object and add values to it later. You can add values to a set using add() method. This method accepts either one value or an iterable. Iterable means an array of values.

So, you can either pass in values one by one, or you can pass in an array with values. Both will work. Remember that set accepts all primitive data types as well as objects.

#web-development #javascript-development #programming #development #javascript

Introduction to Sets in JavaScript
1.35 GEEK