Middle
Have you ever encountered Set objects? What is their feature and why were they created?
sobes.tech AI
Answer from AI
Set objects in JavaScript are collections of unique values. Unlike arrays, Set automatically excludes duplicates, which is convenient when you need to store only unique elements.
Features of Set:
- Stores only unique values of any type (primitives and objects).
- The order of elements is preserved in the order of insertion.
- Fast search and existence check of an element via the
has()method.
Example usage:
const mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add(1); // will not be added, since 1 already exists
console.log(mySet.has(5)); // true
console.log(mySet.size); // 2
Set is designed for convenient management of unique data sets without the need to manually check for the presence of elements.