Js Set Methods in JavaScript
?? JavaScript Set Methods
A Set is a collection of unique values — no duplicates allowed.
Creating a Set
const mySet = new Set([1, 2, 3, 4]);Common Set Methods
| Method | Description | Example |
|---|---|---|
add(value) | Adds a new element to the set | mySet.add(5); |
delete(value) | Removes an element if it exists | mySet.delete(2); |
has(value) | Checks if an element exists, returns true or false | mySet.has(3); // true |
clear() | Removes all elements | mySet.clear(); |
size (property) | Returns number of elements | mySet.size; // 4 |
values() | Returns an iterator for the set values | for (let val of mySet.values()) |
Example Usage
const mySet = new Set();mySet.add(1);mySet.add(2);mySet.add(2); // Duplicate ignoredconsole.log(mySet.size); // 2console.log(mySet.has(1)); // truemySet.delete(1);console.log(mySet.has(1)); // falsemySet.clear();console.log(mySet.size); // 0Iterating Over a Set
const mySet = new Set(['a', 'b', 'c']);for (let item of mySet) { console.log(item);}// Output:// a// b// cIf you want, I can explain more about Set vs Array or advanced methods like forEach() on Sets!