JavaScript : Sets

In JavaScript, a Set is a built-in data structure that represents a collection of unique values. Unlike arrays, Sets do not allow duplicate elements, which means each element within a Set must be unique. Sets are iterable, meaning you can loop through their elements using for...of loops or iterate over them using the forEach() method.

Creating a Set:


You can create a Set by passing an iterable object (such as an array) to the Set() constructor, or by using the Set literal notation {} .


// Using Set constructor
const mySet1 = new Set([1, 2, 3, 4, 4]); // Duplicate value '4' will be ignored

// Using Set literal notation
const mySet2 = new Set(['a', 'b', 'c']);

 

Adding and Removing Elements:


Sets have methods for adding and removing elements:

  • add(value) : Adds a new element to the Set. If the value already exists in the Set, it is ignored.
  • delete(value) : Removes the specified value from the Set. Returns true if the value was removed successfully, otherwise false.
  • clear() : Removes all elements from the Set.


const mySet = new Set();

mySet.add('apple');
mySet.add('banana');
mySet.add('apple'); // Ignored, as 'apple' already exists in the Set

console.log(mySet); // Output: Set { 'apple', 'banana' }

mySet.delete('banana');
console.log(mySet); // Output: Set { 'apple' }

mySet.clear();
console.log(mySet); // Output: Set {}

 

Iterating Over Sets:


Sets are iterable, so you can loop through their elements using for...of loops or use the forEach() method.


const mySet = new Set(['a', 'b', 'c']);

// Using for...of loop
for (let item of mySet) {
  console.log(item);
}

// Using forEach method
mySet.forEach(item => {
  console.log(item);
});

 

Set Size and Checking for Elements:


Sets have properties and methods to check their size and whether a value exists in the Set:

  • size : Returns the number of elements in the Set.
  • has(value) : Returns true if the Set contains the specified value, otherwise false .


const mySet = new Set(['a', 'b', 'c']);

console.log(mySet.size); // Output: 3

console.log(mySet.has('a')); // Output: true
console.log(mySet.has('d')); // Output: false

 

Sets are useful for storing unique values and performing operations like union, intersection, and difference. They provide a convenient way to work with collections of data in JavaScript.