- Courses
- đ»Programming Languages
- đJavaScript
- Core Objects
- Sets
On this page
Sets in JavaScript
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
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];
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Maps
Next
Promises
- Creating a Set
- Adding Values
- Checking Values
- Size of a Set
- Deleting a Value
- Removing All Values
- Iterating Over a Set
- Converting a Set to an Array
