Junior — Middle
Explain the concept of the Set collection in JavaScript and its main features
sobes.tech AI
Answer from AI
The JavaScript Set collection is a data structure that stores unique values of any type, whether primitives or objects. Main features of Set:
- Stores only unique elements; duplicates are automatically ignored.
- Elements are ordered by insertion order.
- Allows quick existence checks with the
has()method. - Supports methods like
add(),delete(),clear(), and iteration.
Example usage:
const mySet = new Set();
mySet.add(1);
mySet.add(5);
mySet.add(1); // will not be added again
console.log(mySet.has(5)); // true
mySet.delete(1);
console.log(mySet.size); // 1
for (const item of mySet) {
console.log(item);
}