JavaScript Set - Concise Notes ๐
๐น What is a Set?
A Set is a built-in JavaScript object that stores unique values (no duplicates).
๐น Creating a Set
const mySet = new Set([1, 2, 3, 4, 5]);
๐น Key Methods
| Method | Description | Example Usage |
|---|---|---|
.add(value) |
Adds a value to the Set | mySet.add(6); |
.delete(value) |
Removes a value | mySet.delete(3); |
.has(value) |
Checks if value exists | mySet.has(2); // true |
.clear() |
Removes all elements | mySet.clear(); |
.size |
Returns the number of elements | mySet.size; // 5 |
๐น Iterating Over a Set
mySet.forEach(value => console.log(value)); // Loop using forEach
for (let value of mySet) console.log(value); // Loop using for...of
๐น Convert Set to Array
const numArray = [...mySet];
๐น Convert Array to Set (Remove Duplicates)
const uniqueNums = new Set([1, 2, 2, 3, 4]); // {1, 2, 3, 4}
๐น When to Use a Set?
โ
Fast lookups (O(1))
โ
Removing duplicates
โ
Tracking unique values
๐ Best for performance when working with unique data!
Top comments (0)