In JavaScript, a Set is a collection of unique values, where each value may occur only once within the Set. Sets are useful for storing a collection of distinct elements and efficiently performing operations like adding, removing, and checking for the presence of elements
Key Characteristics:
- Unique Values:
- A Set contains only unique values; duplicates are not allowed. Therefore, each value in a Set occurs only once.
No Key-Value Pairs:
- Unlike maps, Sets do not have key-value pairs. Each value in a Set is treated as both a key and a value.
Dynamic Size:
- Sets in JavaScript can grow or shrink dynamically, allowing you to add or remove values as needed without specifying the size in advance.
Iterability:
- Sets are iterable, meaning you can loop through their elements using various iteration methods like
forEach
,for...of
, orentries
.
- Sets are iterable, meaning you can loop through their elements using various iteration methods like
Data Types:
- Sets can store values of any data type, including primitive types (such as numbers, strings, and booleans) and object references.
Ordering:
- The order of elements in a Set is based on the insertion order, meaning the elements maintain the order in which they were inserted.
Operations:
Add (Insertion):
- Adds a new value to the Set. If the value is already present, it is not added again.
set.add(value);
Delete (Removal):
- Removes a value from the Set if it exists.
set.delete(value);
Has (Existence Check):
- Checks if the Set contains a specific value.
if (set.has(value)) {
// Value exists in the Set
}
Size:
- Returns the number of elements in the Set
let size = set.size;
Clear:
- Removes all elements from the Set, making it empty.
set.clear();
Example Implementation:
// Creating a new Set
let mySet = new Set();
// Adding values to the Set
mySet.add(1);
mySet.add("Hello");
mySet.add(true);
// Checking if a value exists
if (mySet.has(1)) {
console.log
("Value 1 exists in the Set");
}
// Removing a value
mySet.delete("Hello");
// Iterating over the Set
mySet.forEach(value => {
console.log(value);
});
Use Cases:
- Eliminating duplicate elements from an array.
- Storing a collection of unique identifiers or keys.
- Performing set operations such as union, intersection, and difference.
- Implementing membership checks or filtering unique values.