JavaScript Set Methods
8 April 2025 | Category: JavaScript
JavaScript Set
objects come with built-in methods that help you manage unique collections of values.
A Set
ensures no duplicates, and you can perform various operations like adding, removing, and checking values.
âś… List of Common Set Methods
Method | Description |
---|---|
add(value) | Adds a new value |
delete(value) | Removes a specific value |
has(value) | Checks if a value exists |
clear() | Removes all values from the Set |
values() | Returns an iterator of Set values |
forEach(callback) | Loops through each value in the Set |
size | Returns the number of values (property) |
🔹 add(value)
Adds a new unique value to the Set.
const items = new Set();
items.add("pen");
items.add("book");
items.add("pen"); // duplicate - ignored
console.log(items); // Set(2) { "pen", "book" }
🔹 delete(value)
Removes a value from the Set.
items.delete("pen");
console.log(items); // Set(1) { "book" }
🔹 has(value)
Checks if a value exists in the Set.
console.log(items.has("book")); // true
console.log(items.has("pen")); // false
🔹 clear()
Deletes all elements in the Set.
items.clear();
console.log(items); // Set(0) {}
🔹 values()
or keys()
Returns an iterator of the Set’s values.
const letters = new Set(["a", "b", "c"]);
for (let letter of letters.values()) {
console.log(letter);
}
Note:
keys()
is an alias forvalues()
in Set (for consistency withMap
).
🔹 forEach(callback)
Loops through each value in the Set.
letters.forEach(value => {
console.log(value);
});
🔹 .size
Property
Gives the total number of values in the Set.
console.log(letters.size); // 3
đź§ľ Quick Example: All Methods in One
const numbers = new Set();
numbers.add(1);
numbers.add(2);
numbers.add(3);
console.log(numbers.has(2)); // true
numbers.delete(3);
console.log(numbers.size); // 2
numbers.forEach(num => console.log(num)); // 1 2
numbers.clear();
console.log(numbers.size); // 0
âś… Summary Table
Method / Property | Purpose |
---|---|
add() | Add a value |
delete() | Delete a specific value |
has() | Check if value exists |
clear() | Remove all values |
values() | Get iterator of values |
forEach() | Loop through values |
size | Get number of values (read-only) |