Sets in JavaScript¶
A Set is a collection of unique values of any type, whether primitive values or object references.
Each value can only occur once within the set.
Creating a Set¶
You can create a Set using the new Set() syntax.
let set = new Set();
Adding Values¶
The add method is used to add a value to the set. If the value is already in the set, it does not get added again since all values in a set must be unique.
set.add('value1');
Checking Values¶
The has method is used to check if a value exists in the set.
console.log(set.has('value1')); // Outputs: true
Size of a Set¶
The size property returns the number of values in the set.
console.log(set.size); // Outputs: 1
Deleting a Value¶
The delete method removes a value by its value.
set.delete('value1');
console.log(set.has('value1')); // Outputs: false
Removing All Values¶
The clear method removes all values from the set.
set.clear();
console.log(set.size); // Outputs: 0
Iterating Over a Set¶
You can use for...of loop or forEach method to iterate over a Set. It returns values in the insertion order.
set.add('value1');
set.add('value2');
for (let value of set) {
console.log(value);
}
// OR
set.forEach(function(value) {
console.log(value);
});
Converting a Set to an Array¶
You can convert a Set to an Array using the spread operator (...).
let array = [...set];