Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!
To create a new Set, you can use the following syntax:
const mySet = new Set();
This will create an empty Set. You can also pass an iterable object to the Set constructor to initialize it with values:
const mySet = new Set([1, 2, 3]);
To add values to a Set, you can use the
This will add the value 4 to the Set. If you try to add a value that already exists in the Set, it will be ignored.
To check if a value exists in a Set, you can use the
mySet.has(4); // true
This will return true if the value exists in the Set, and false otherwise.
To remove a value from a Set, you can use the
This will remove the value 4 from the Set.
You can also get the size of a Set using the
mySet.size; // 3
This will return the number of values in the Set.
One of the main benefits of using a Set is that it automatically removes duplicates. For example:
const mySet = new Set([1, 2, 2, 3, 3, 3]);
This will create a Set with the values 1, 2, and 3. The duplicates are automatically removed.