JavaScript JS Tutorial JS Objects JS Functions JS Classes JS Async JS HTML DOM JS Browser BOM JS Web APIs JS AJAX JS JSON JS vs jQuery JS Graphics



JS Sets

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.

Creating a Set

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>

Adding and Removing Values

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>

Checking if a Value Exists

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>

Iterating Over a Set

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>

Converting a Set to an Array

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>

Conclusion

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.

References

Activity