What is a Set in JavaScript?
Last Updated :
31 Jan, 2024
In JavaScript, a Set
is a built-in object that allows you to store unique values of any data type, whether primitive values or object references. Unlike arrays, which can contain duplicate values and are ordered by index, a Set
only holds distinct values, and the order of insertion is maintained.
Here are the key characteristics of a Set
:
- Uniqueness: A
Set
can only contain unique values. If you attempt to add a duplicate value, it will be ignored. This uniqueness is determined using the “SameValueZero” equality comparison algorithm, which is similar to the strict equality (===
) operator.
- Iterable:
Set
objects are iterable, which means you can use methods like forEach
or for...of
loop to iterate through the values.
- No Index: Unlike arrays,
Set
objects do not have indexes or keys associated with their elements. You access elements directly through the Set
methods.
- Methods:
Set
provides methods for adding, deleting, and checking the existence of values. Common methods include add
, delete
, has
, and clear
.
Example: Here, mySet
is created, values are added using the add
method, and existence is checked using the has
method. The delete
method removes a value, and the forEach
method is used to iterate over the elements.
Javascript
const mySet = new Set();
mySet.add(1);
mySet.add( 'Hello' );
mySet.add({ key: 'value' });
console.log(mySet.has(1));
console.log(mySet.has( 'Hello' ));
console.log(mySet.has({ key: 'value' }));
mySet. delete ( 'Hello' );
mySet.forEach(value => {
console.log(value);
});
|
Output
true
true
false
1
{ key: 'value' }
Share your thoughts in the comments
Please Login to comment...