In JavaScript, Set
is a built-in object that allows you to store unique values of any type, whether primitive values or object references. The Set
object was introduced in ECMAScript 2015 (ES6) and provides a simple and efficient way to manage a collection of unique values.
Here's a brief explanation of Set
:
-
Unique Values:
- A
Set
can only contain unique values. If you try to add a duplicate value, it won't be added, and the set will remain unchanged.
- A
-
Creation:
- You can create a new
Set
using thenew Set()
constructor. You can also initialize aSet
with an iterable, such as an array.
const mySet = new Set();
or
const mySet = new Set([1, 2, 3, 4, 5]);
- You can create a new
-
Adding and Removing Elements:
- You can add an element to a
Set
using theadd
method:
mySet.add(6);
- You can add an element to a
-
To remove an element, you can use the
delete
method:
mySet.delete(3);
-
Checking for Existence:
- You can check if a value exists in a
Set
using thehas
method:
console.log(mySet.has(3)); // Returns false after deleting 3
- You can check if a value exists in a
-
Size:
- The
size
property returns the number of elements in aSet
:
console.log(mySet.size); // Returns the number of elements
- The
-
Iteration:
- You can iterate through the elements of a
Set
using methods likeforEach
or thefor...of
loop:
mySet.forEach(value => { console.log(value); });
or
for (const value of mySet) { console.log(value); }
- You can iterate through the elements of a
-
Clearing the Set:
- The
clear
method removes all elements from theSet
:
mySet.clear();
- The
Set
is particularly useful when you need to maintain a collection of unique values without duplicates. It provides a convenient and performant way to handle such scenarios.