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.
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']);
Sets have methods for adding and removing elements:
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 {}
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);
});
Sets have properties and methods to check their size and whether a value exists in the Set:
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.