In JavaScript, a Set is a built-in object that allows you to store unique values of any type, whether primitive values or object references. Unlike arrays, sets are unordered collections, and they do not allow duplicate elements. This makes them particularly useful for tasks like removing duplicates from arrays or managing collections where uniqueness is required.
Sets
What is a Set?
Creating a Set
You can create a new set by passing an iterable (like an array) to the Set constructor.
const mySet = new Set([1, 2, 3, 4, 5]);
This will create a set containing the numbers 1 through 5. If there are duplicate values in the iterable, they will be automatically removed.
Characteristics of a Set
- Uniqueness: Each value in a set must be unique. Adding a duplicate value has no effect.
- Sets are unordered, meaning there is no guarantee of element order.
- Unlike arrays, sets do not support accessing elements by index.
To check if a value is a set, you can use the
instanceof
operator.
console.log(mySet instanceof Set); // Returns true
Set Methods
add(value):
Adds a new element to the set. If the value already exists, the set remains unchanged.
mySet.add(6);
clear():
Removes all elements from the set.
mySet.clear(); // The set is now empty
delete(value):
Removes a specified value from the set. Returns true if the value was present and removed, or false otherwise.
mySet.delete(3); // Removes the value 3 from the set
has(value):
Checks if a value exists in the set. Returns true if present, false otherwise.
mySet.has(2); // Returns true if 2 is in the set
size:
Returns the number of elements in the set.
console.log(mySet.size); // Outputs the number of elements in the set
update():
Adds the items of another set to this set.