The Ultimate Guide to JavaScript Sets: Everything You Need to Know

JavaScript provides developers with a variety of built-in objects that make working with data and collections much easier. One such object that is incredibly useful but often overlooked is the Set.

In this comprehensive guide, we‘ll dive deep into everything you need to know about JavaScript Sets – what they are, how they work, and how you can leverage them in your own code. Whether you‘re a JavaScript beginner or an experienced developer looking to level up your skills, understanding Sets is essential. Let‘s jump right in!

What is a JavaScript Set?

First, let‘s define what a Set is. A Set is a built-in object in JavaScript that allows you to store unique values of any type, whether primitive values or object references.

Sets are similar to Arrays in that they are both used to store collections of data. However, there are a few key differences:

  • Items in a Set are unique. A Set cannot contain duplicate values.
  • Items in a Set are not indexed and cannot be accessed by a numeric index like with arrays.
  • Sets are iterable, allowing you to loop through the items they contain.

One of the major benefits of Sets is that checking if an item exists in a Set is much faster than checking if an item exists in an Array. This is because Set lookups are based on hashtables, providing 0(1) lookup performance, while Array lookups require iterating through the entire Array.

Creating a New Set

To create a new Set, you use the Set constructor, optionally passing in an iterable object (like an Array) containing the values you want to add to the Set:

const set1 = new Set(); // creates an empty set 
console.log(set1); // Set(0) {}

const set2 = new Set([1, 2, 3, 3]); // creates a set with values
console.log(set2); // Set(3) {1, 2, 3}

Notice in the set2 example, even though we passed in a duplicate value of 3, the resulting Set only contains unique values.

Adding and Removing Items

To add a single item to a Set, you use the add() method:

const set = new Set();
set.add(1);
set.add(5);
set.add(‘some text‘);

To remove a single item, use the delete() method:

set.delete(1);

If you want to remove all items from a Set, use clear():

set.clear(); 
console.log(set); // Set(0) {}

Unique Properties of Sets

As mentioned earlier, Sets have a few unique properties that differentiate them from Arrays:

  1. Each value in a Set is unique. Trying to add a duplicate value will have no effect.
  2. Set items are not indexed. You cannot access them by index number like set[0].
  3. The order of items in a Set is based on insertion order.
  4. NaN and undefined can also be stored in a Set.
  5. Sets can contain a mix of different data types – numbers, strings, booleans, objects, even other Sets.

Common Set Methods

Sets come with a variety of convenient built-in methods for working with the items they contain:

  • add(value): appends a new element with the given value to the Set. Returns the Set object.
  • clear(): removes all elements from the Set object.
  • delete(value): removes the element associated to the value. Returns a boolean.
  • has(value): returns a boolean indicating whether an element with the specified value exists in the Set or not.
  • forEach(callbackFn, thisArg): calls callbackFn once for each value in the Set, in insertion order.
  • values(): returns a new Iterator object that contains the values for each element in the Set, in insertion order.
  • keys(): same as values(). Kept for compatibility with Map objects.

Here‘s an example showing some of these methods in action:

const set = new Set([1, 2, 3]);

console.log(set.has(1)); // true 
console.log(set.has(4)); // false

set.add(4);
console.log(set.has(4)); // true

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

set.clear(); 
console.log(set); // Set(0) {}

Iterating Over Sets

You can easily iterate over the items in a Set using a for...of loop or the forEach() method:

const set = new Set([1, 2, 3]);

// iterate with for...of 
for (const value of set) {
  console.log(value);
}

// iterate with forEach 
set.forEach(value => {
  console.log(value);
});

Both of these will log out:

1
2
3

Sets vs Arrays

So when should you use a Set vs an Array? Here are some things to consider:

  • Use a Set when you need to store unique values and the order doesn‘t matter. Checking if a Set contains an item is faster than with an Array.

  • Use an Array when you need indexed access to items, when order matters, and when you need to store duplicate values.

  • Converting between Sets and Arrays is easy with the spread operator:

const set = new Set([1, 2, 3]);
const array = [...set]; // convert Set to Array 

const array2 = [4, 5, 6];
const set2 = new Set(array2); // convert Array to Set

Set Examples

Let‘s look at a couple practical examples of using Sets.

  1. Remove duplicate items from an array:
const numbers = [1, 1, 2, 2, 5, 5, 4];
const uniqueNums = [...new Set(numbers)];
console.log(uniqueNums); // [1, 2, 5, 4]
  1. Check for the presence of an item:
const books = new Set();

books.add(‘Pride and Prejudice‘);
books.add(‘The Great Gatsby‘);

alert(books.has(‘The Great Gatsby‘)); // true
alert(books.has(‘Jane Eyre‘)); // false
  1. Implementing a basic Set-based cache:
    
    const cache = new Set();

const getVastData = id => {
if(cache.has(id)) {
return cache.get(id);
}
else {
const data = expensiveOperation(id);
cache.add(id, data);
return data;
}
};



<h2>Best Practices</h2>

To wrap up, here are some best practices to keep in mind when working with Sets:

1. Use a Set when storing unique values. They provide better performance than arrays for this use case.

2. Sets shine when you need to frequently test if items are present. The `has()` method is 0(1) vs 0(n) for arrays.

3. When you need to frequently add/remove items, Sets scale better than arrays.

4. Don‘t use Sets when you need indexed access to items or when order is important. Arrays are better suited for those use cases.

5. The Set methods `keys()` and `values()` return the same iterator object, for compatibility with Map objects. Usually you‘ll just want `values()`.

<h2>Conclusion</h2>

JavaScript Sets are a powerful and underutilized built-in object that every developer should have in their toolbelt. Their unique properties, like guaranteeing item uniqueness and optimized item lookups, make them incredibly useful in a variety of situations.

In this guide, we‘ve covered everything you need to know about Sets, from the basics of creating Sets and adding/removing items, to more advanced usage like converting between Sets and Arrays and practical use case examples.

So next time you find yourself working with a collection of data items, consider reaching for a Set. With their performance benefits and handy built-in methods, they might just be the perfect tool for the job!

Similar Posts