JavaScript(JS) Set
In JavaScript, a Set
is a built-in data structure that allows you to store unique values of any type. It is similar to an array, but with a few key differences.
One of the main differences between a Set
and an array is that a Set
can only contain unique values. If you try to add a value that already exists in the Set
, it will be ignored. Additionally, a Set
does not maintain the order of its values, whereas arrays are ordered.
Here are some examples of using a Set
in JavaScript:
- Creating a
Set
:
let mySet = new Set();
This creates a new empty Set
instance.
- Adding and retrieving values from a
Set
:
let mySet = new Set(); mySet.add("value1"); mySet.add("value2"); console.log(mySet.has("value1")); // output: true console.log(mySet.has("value3")); // output: false
In this example, we add two values to the Set
using the add()
method, and then check if the Set
contains a value using the has()
method.
- Iterating over a
Set
:
let mySet = new Set(); mySet.add("value1"); mySet.add("value2"); for (let value of mySet) { console.log(value); }
In this example, we use a for...of
loop to iterate over the values in the Set
and log each value to the console.
- Removing values from a
Set
:
let mySet = new Set(); mySet.add("value1"); mySet.add("value2"); mySet.delete("value1"); console.log(mySet.has("value1")); // output: false
In this example, we remove a value from the Set
using the delete()
method, and then check if the Set
contains the value using the has()
method.