Exploring the Universe of Sets in JavaScript
Understanding JavaScript Sets
Let's begin with Sets. In JavaScript, a Set is a unique type of object that stores various data types, either primitive or objects. A Set does not contain duplicates. Think of a Set as a cosmic bag holding celestial bodies (elements), ensuring that each remains one-of-a-kind.
The array includes duplicates. The set, in contrast, displays only unique values.
Creating and Adding Elements in a Set
The creation of a Set involves the new keyword and the Set() method. You can add items using the .add() method.
In this case, 'Star' was added twice, but the Set retains it as a single entry to prevent duplication.
Removing Elements from a Set
To remove entries from a Set, use the .delete() method. If you want to clear a Set entirely, use the .clear() method.
The code above first removed the 'Star' from our Universe. Then, the .clear() method entirely emptied the Set, leaving it unoccupied.
Checking a Set's Size and Membership
We inspect the size of a Set or its total entries using the size property. The .has() method checks whether an element exists in the Set.
In this code, our universe contains four elements — two planets (Planet and Moon), an asteroid, and a star. Consequently, the size is 4. The .has() method found 'Star' but couldn't find 'Galaxy'.
Lesson Summary and Practice
