In JavaScript, the Set
object is a data structure that represents a collection of unique values. Set methods provide various functions to process and manage this collection. In this blog post, we will explain the Set methods available in JavaScript and demonstrate each with example code.
- add() Method:
This method adds a new value to a Set object.
let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
console.log(mySet); // Set(3) {1, 2, 3}
- delete() Method:
This method removes a specific value from a Set object.
mySet.delete(2);
console.log(mySet); // Set(2) {1, 3}
- has() Method:
This method checks if a specific value is present in a Set object.
console.log(mySet.has(1)); // true
console.log(mySet.has(2)); // false
- clear() Method:
This method removes all elements from a Set object.
mySet.clear();
console.log(mySet); // Set(0) {}
- size Property:
This property returns the number of elements in a Set object.
console.log(mySet.size); // 0
- forEach() Method:
This method calls a specified function for each element in a Set object.
mySet.add('a');
mySet.add('b');
mySet.add('c');
mySet.forEach(function(value) {
console.log(value);
});
// a
// b
// c
Conclusion:
Set methods make it easy to manage unique values in JavaScript. These methods are very useful for basic operations like adding or removing elements, and iterating over collections. With the examples provided, you’ve learned about Set methods and can now use them in your own projects.