Sets In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Sets In JavaScript.
Sets In JavaScript
In JavaScript, a Set is a collection of unique values. It can store any type of value, including primitive types (such as numbers, strings, and booleans) and object references. Sets are similar to arrays, but they do not have any order and the values they store must be unique.
Here’s an example of how to create a Set in JavaScript:
let set = new Set();
You can also create a Set with an initial set of values, like this:
let set = new Set([1, 2, 3, 4, 5]);
You can add new values to a Set using the add()
method, like this:
set.add(6);
You can check if a value is in a Set using the has()
method, like this:
if (set.has(6)) {
console.log("The set contains the value 6.");
}
You can remove a value from a Set using the delete()
method, like this:
set.delete(6);
You can loop through the values in a Set using a for...of
loop, like this:
for (let value of set) {
console.log(value);
}
You can also use the size
property to get the number of values in a Set, like this:
console.log(set.size);
Sets also have other useful methods like clear()
to clear all the values, keys()
to return an iterator object for the values, values()
to return an iterator object for the values which are same as keys, and entries()
to return an iterator object for the [value, value] pairs.
Conclusion
Sets are useful when you need to store a collection of unique values and you don’t need to maintain any particular order. Sets are also useful when you need to perform operations such as union, intersection, and difference on sets of values.
If you liked this post Sets In JavaScript, then please share this with your friends and make sure to bookmark this website for more awesome content.