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.
JavaScript1let array = [1, 2, 2, 3, 3, 4]; 2let set = new Set([1, 2, 2, 3, 3, 4]); 3 4console.log(array); // [1, 2, 2, 3, 3, 4] 5console.log(set); // Set(4) {1, 2, 3, 4}
The array
includes duplicates. The set
, in contrast, displays only unique values.
The creation of a Set involves the new
keyword and the Set()
method. You can add items using the .add()
method.
JavaScript1let universe = new Set(); 2universe.add('Asteroid'); 3universe.add('Star'); 4universe.add('Planet'); 5universe.add('Star'); 6console.log(universe); // Set(3) {"Asteroid", "Star", "Planet"}
In this case, 'Star'
was added twice, but the Set retains it as a single entry to prevent duplication.
To remove entries from a Set, use the .delete()
method. If you want to clear a Set entirely, use the .clear()
method.
JavaScript1universe.delete('Star'); 2console.log(universe); // Set(2) {"Asteroid", "Planet"} 3universe.clear(); 4console.log(universe); // Set(0) {}
The code above first removed the 'Star'
from our Universe. Then, the .clear()
method entirely emptied the Set, leaving it unoccupied.
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.
JavaScript1universe.add('Asteroid'); 2universe.add('Star'); 3universe.add('Planet'); 4universe.add('Moon'); 5 6console.log(universe.size); // 4 7console.log(universe.has('Star')); // true 8console.log(universe.has('Galaxy')); // false
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'.
Well done, Astronaut! You now understand Sets in JavaScript. We've covered the creation of Sets, the addition and removal of elements, and how to check a Set's size and membership.
Now, apply your new skills in coding challenges to reinforce what you've learned. Are you ready to channel your inner astronaut? Go for it!