So, what exactly are sets in JavaScript? Sets are a built-in data structure that allow you to store unique values of any type, whether it’s a string, number, boolean or even an object. Unlike arrays, sets do not allow duplicates and are not indexed, meaning that you cannot access items by their position in the set.
Let’s take a look at how we can create a set in JavaScript. To create a new set, we can use the Set() constructor function, like so:
const mySet = new Set();
This creates an empty set that we can add values to later.
[Adding and Removing Values]
To add values to a set, we can use the add() method. For example:
mySet.add(‘apple’); mySet.add(‘banana’); mySet.add(‘orange’);
This adds the values ‘apple’, ‘banana’, and ‘orange’ to the set.
To remove a value from a set, we can use the delete() method. For example:
mySet.delete(‘banana’);
This removes the value ‘banana’ from the set.
To check if a value is in a set, we can use the has() method.
For example:
mySet.has(‘apple’); // returns true mySet.has(‘banana’); // returns false
This checks if the value ‘apple’ is in the set and returns true. It also checks if the value ‘banana’ is in the set and returns false.
To iterate over the values in a set, we can use the forEach() method.
For example:
mySet.forEach((value) => { console.log(value); });
This prints out each value in the set to the console.
[Conclusion]
And that’s a brief introduction to JavaScript sets! We’ve learned what sets are, how to create them, add and remove values, check if a value is in a set, and iterate over the values in a set. Sets can be a powerful tool in your JavaScript programming, so be sure to give them a try in your next project.