What is a Set in JavaScript?
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 likeforEach
orfor...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 theSet
methods. - Methods:
Set
provides methods for adding, deleting, and checking the existence of values. Common methods includeadd
,delete
,has
, andclear
.
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
// Creating a Set const mySet = new Set(); // Adding values to the Set mySet.add(1); mySet.add( 'Hello' ); mySet.add({ key: 'value' }); // Checking existence console.log(mySet.has(1)); // Output: true console.log(mySet.has( 'Hello' )); // Output: true console.log(mySet.has({ key: 'value' })); // Deleting a value mySet. delete ( 'Hello' ); // Iterating through the Set mySet.forEach(value => { console.log(value); }); // Output: // 1 // [object Object] |
Output
true true false 1 { key: 'value' }
Contact Us