Open In App

What is a Set in JavaScript?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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' }

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads