JavaScript Sets Overview
A Set in JavaScript is a built-in object that stores unique values of any type, whether primitive or reference. Unlike arrays, sets do not allow duplicate entries and do not maintain an index-based order.
1. Creating a Set
// Using the Set constructor
const numbers = new Set([1, 2, 3, 4]);
console.log(numbers); // Set {1, 2, 3, 4}
// Empty set
const emptySet = new Set();
2. Key Features
- Stores unique values only (duplicates are ignored).
- Values can be of any type: numbers, strings, objects, arrays, or even other sets.
- Order is insertion-based but no numeric index access.
- Iterable: you can loop through a set with
for...of
or.forEach()
.
3. Common Set Methods
Method | Description | Example |
---|---|---|
add(value) | Adds a new element | numbers.add(5); |
delete(value) | Removes a value | numbers.delete(2); |
has(value) | Checks if value exists | numbers.has(3); // true |
clear() | Removes all elements | numbers.clear(); |
size | Returns the number of elements | numbers.size; // 4 |
4. Iterating Over a Set
const fruits = new Set(["apple", "banana", "mango"]);
// Using for...of
for (const fruit of fruits) {
console.log(fruit);
}
// Using forEach
fruits.forEach(fruit => console.log(fruit));
5. Converting Between Sets and Arrays
Array → Set: Removes duplicates automatically.
const nums = [1, 2, 2, 3, 4];
const uniqueNums = new Set(nums);
console.log(uniqueNums); // Set {1, 2, 3, 4}
Set → Array: Use spread operator or Array.from()
.
const arr = [...uniqueNums]; // [1, 2, 3, 4]