JavaScript Sets come with several methods to manipulate and interact with the elements they contain. Below are the commonly used Set methods:
1. add(value)
Adds a new element to the Set. If the element already exists, it is ignored since Sets only store unique values.
let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(2); // Duplicate, won't be added
console.log(mySet); // Set { 1, 2 }
2. delete(value)
Removes a specific element from the Set. Returns true if the element was successfully removed, otherwise false.
mySet.delete(1); // true
console.log(mySet); // Set { 2 }
3. has(value)
Checks if a value exists in the Set. Returns true if the value is present, otherwise false.
console.log(mySet.has(2)); // true console.log(mySet.has(1)); // false
4. clear()
Removes all elements from the Set.
mySet.clear();
console.log(mySet); // Set {}
5. size
Returns the number of elements in the Set.
let anotherSet = new Set([1, 2, 3]); console.log(anotherSet.size); // 3
6. forEach(callbackFn, thisArg)
Executes a provided function once for each value in the Set, in insertion order. Optionally, you can provide a thisArg to use as this value inside the callback function.
anotherSet.forEach((value) => {
console.log(value); // Logs 1, 2, 3
});
7. values()
Returns a new Iterator object containing the values for each element in the Set in insertion order. It’s the default iterator for a Set.
let iterator = anotherSet.values(); console.log(iterator.next().value); // 1
8. keys()
Since Sets only have values (no keys), this method is identical to values() and exists for compatibility with the Map object.
let keysIterator = anotherSet.keys(); console.log(keysIterator.next().value); // 1
9. entries()
Returns a new Iterator object containing an array of [value, value] for each element in the Set. This is similar to Map‘s entries() method for compatibility.
let entriesIterator = anotherSet.entries(); console.log(entriesIterator.next().value); // [1, 1]
10. Symbol.iterator
The default iterator for Sets, which is the same as the values() method.
for (let value of anotherSet) {
console.log(value); // Logs 1, 2, 3
}
Example:
let mySet = new Set([1, 2, 3]);
mySet.add(4);
mySet.add(3); // Won't be added
console.log(mySet.has(2)); // true
console.log(mySet.size); // 4
mySet.delete(1);
console.log(mySet); // Set { 2, 3, 4 }
mySet.forEach((value) => console.log(value)); // 2, 3, 4
mySet.clear();
console.log(mySet.size); // 0
Summary:
JavaScript Set methods offer powerful tools for managing collections of unique values. Understanding these methods can help you efficiently manipulate and query Sets in your applications.