Open In App

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:



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.




// 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' }
Article Tags :