What is Sets in JavaScript | JavaScript Tutorials in Hindi | Interview Question #46
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. It’s similar to an array, but with some differences:
- Uniqueness: Sets only allow unique values. If you try to add a value that already exists in the Set, it will not be added again.
- Ordering: Sets maintain the insertion order of elements, which means you can iterate through the elements in the order they were added.
- No Duplicate Elements: When you try to add a duplicate element to a Set, it won’t throw an error, but it also won’t add the duplicate element. This property makes Sets useful for tasks where you need to ensure uniqueness.
Here’s a basic example of how you can use a Set in JavaScript:
let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(1); // Won't be added because it's a duplicate
console.log(mySet); // Output: Set(3) { 1, 2, 3 }
console.log(mySet.has(2)); // Output: true
mySet.delete(2);
console.log(mySet); // Output: Set(2) { 1, 3 }
mySet.forEach((value) => {
console.log(value);
});
// Output:
// 1
// 3
Sets can be quite handy for tasks like removing duplicates from an array, checking for the presence of unique values, or even as a more efficient alternative to arrays in some situations.