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.

JavaScript
let array = [1, 2, 2, 3, 3, 4];
let set = new Set([1, 2, 2, 3, 3, 4]);

console.log(array); // [1, 2, 2, 3, 3, 4]
console.log(set); // Set(4) {1, 2, 3, 4}

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.

JavaScript
let universe = new Set();
universe.add('Asteroid');
universe.add('Star');
universe.add('Planet');
universe.add('Star');
console.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.

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.

JavaScript
universe.delete('Star'); 
console.log(universe); // Set(2) {"Asteroid", "Planet"}
universe.clear();
console.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.

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.

JavaScript
universe.add('Asteroid');
universe.add('Star');
universe.add('Planet');
universe.add('Moon');

console.log(universe.size); // 4
console.log(universe.has('Star')); // true
console.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'.

Lesson Summary and Practice

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal