JavaScript Set Methods
A Set in JavaScript provides several built-in methods to add, remove, check, and iterate over elements.
1. add()
Adds a new value to the Set. Duplicate values are ignored.
- Returns the Set itself (can be chained).
- Maintains insertion order.
const numbers = new Set();
numbers.add(1);
numbers.add(2);
numbers.add(2); // Duplicate ignored
console.log(numbers); // Set { 1, 2 }
2. delete()
Removes a specific value from the Set.
true
if the value existed and was removed.false
if the value did not exist.
const numbers = new Set([1, 2, 3]);
numbers.delete(2);
console.log(numbers); // Set { 1, 3 }
3. has()
Checks if a value exists in the Set.
const numbers = new Set([1, 2, 3]);
console.log(numbers.has(2)); // true
console.log(numbers.has(4)); // false
4. clear()
Removes all elements from the Set.
const numbers = new Set([1, 2, 3]);
numbers.clear();
console.log(numbers); // Set {}
5. size
Returns the number of unique elements in the Set.
const numbers = new Set([1, 2, 3]);
console.log(numbers.size); // 3
6. entries()
Returns an iterator of [value, value]
pairs (for Map compatibility).
const numbers = new Set([1, 2]);
console.log([...numbers.entries()]); // [[1,1],[2,2]]
7. keys()
Returns an iterator of the Set’s values (same as values()
).
console.log([...numbers.keys()]); // [1, 2]
8. values()
Returns an iterator of the Set’s values (redundant with keys()
but part of the API).
console.log([...numbers.values()]); // [1, 2]
9. Iterating Over a Set
Sets are iterable. You can loop over them using:
a. for...of
Loop
const numbers = new Set([1, 2, 3]);
for (const num of numbers) {
console.log(num);
}
// Output: 1, 2, 3
b. forEach()
Method
numbers.forEach((value) => console.log(value));
// Output: 1, 2, 3
c. Spread Operator
const numbersArray = [...numbers];
console.log(numbersArray); // [1, 2, 3]
10. Converting Set to Array
Sets can be easily converted to arrays for further operations:
const numbers = new Set([1, 2, 3]);
const numbersArray = Array.from(numbers);
console.log(numbersArray); // [1, 2, 3]
Summary Table of Key Set Methods
Method / Property | Description |
---|---|
add(value) | Adds a new element to the Set |
delete(value) | Removes a specific element |
has(value) | Checks if a value exists |
clear() | Removes all elements |
size | Returns the number of elements |
forEach() | Executes a function for each element |
Spread / Array.from() | Convert Set to Array |