
JavaScript Set
JavaScript Set
is a built-in object that represents a collection of unique values, where each value can occur only once. It provides methods for adding, removing, and checking the presence of elements in the set. Here’s an example of how to use Set
:
// Create a new Set
const mySet = new Set();
// Add elements to the Set
mySet.add('Apple');
mySet.add('Banana');
mySet.add('Orange');
// Get the size of the Set
console.log(mySet.size); // Output: 3
// Check if an element exists in the Set
console.log(mySet.has('Apple')); // Output: true
// Remove an element from the Set
mySet.delete('Banana');
// Iterate over the elements in the Set
mySet.forEach((value) => {
console.log(value);
});
// Output:
// Apple
// Orange
// Clear all elements from the Set
mySet.clear();
// Check if the Set is empty
console.log(mySet.size); // Output: 0
In the above example, we create a Set
called mySet
. We add three elements using the add()
method. We can then check if an element exists using the has()
method, remove an element using the delete()
method, and clear all elements from the set using the clear()
method. We can also get the size of the set using the size
property.
The Set
object preserves the insertion order of the elements, and the elements in the set are iterated in the order of their insertion.
One of the key features of Set
is that it allows you to store unique values only. If you try to add a duplicate value, it will be ignored and not added to the set.
Set
is commonly used when you want to store a collection of values and quickly check for the existence of specific values without worrying about duplicates.