JavaScript Sets are a new data structure introduced in ECMAScript 6 (ES6) that allow developers to store unique values of any type. Sets are similar to arrays, but they only store unique values and do not have any order. This makes them useful for tasks such as removing duplicates from an array or checking if a value exists in a collection.
In this tutorial, we will explore the basics of JavaScript Sets and how to use them in your code.
To create a new Set, you can use the Set constructor:
<script>
const mySet = new Set();
</script>
You can also pass an array to the Set constructor to create a Set with initial values:
<script>
const mySet = new Set([1, 2, 3]);
</script>
To add a value to a Set, you can use the add()
method:
<script>
const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
</script>
To remove a value from a Set, you can use the delete()
method:
<script>
const mySet = new Set([1, 2, 3]);
mySet.delete(2);
</script>
To check if a value exists in a Set, you can use the has()
method:
<script>
const mySet = new Set([1, 2, 3]);
mySet.has(2); // returns true
mySet.has(4); // returns false
</script>
You can use the for...of
loop to iterate over a Set:
<script>
const mySet = new Set([1, 2, 3]);
for (const value of mySet) {
console.log(value);
}
</script>
You can also use the forEach()
method to iterate over a Set:
<script>
const mySet = new Set([1, 2, 3]);
mySet.forEach(value => console.log(value));
</script>
You can convert a Set to an array using the Array.from()
method:
<script>
const mySet = new Set([1, 2, 3]);
const myArray = Array.from(mySet);
</script>
JavaScript Sets are a powerful new data structure that allow developers to store unique values of any type. They are useful for tasks such as removing duplicates from an array or checking if a value exists in a collection. With the methods provided by Sets, developers can easily manipulate and iterate over their data.