DEV Community

Pooja Belaramani
Pooja Belaramani

Posted on

What is a Set in JavaScript? πŸ€”

A Set is a collection of unique values in JavaScript. It allows you to store and manipulate a group of values, and offers several useful methods for working with those values.

Why use Sets? 😎

One of the main advantages of using a Set is that it only allows unique values. This means that you don't have to worry about duplicate values in your collection, which can make your code more efficient and easier to read.

Additionally, Sets offer a number of useful methods for working with the values in the collection. For example, you can use the .has() method to check if a specific value is in the Set, the .add() method to add a new value to the Set, and the .delete() method to remove a value from the Set.

How to create a Set in JavaScript? πŸ’ͺ

To create a Set in JavaScript, you can use the new Set() constructor. For example:

const mySet = new Set();
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can pass an array of values to the Set() constructor to create a Set with those values already added. For example:

const mySet = new Set([1, 2, 3, 4]);
Enter fullscreen mode Exit fullscreen mode

Some common Set methods in JavaScript 🧐

Here are some of the most common Set methods in JavaScript, along with a brief description of what they do:

  • .has(): Returns true if the given value is in the Set, and false otherwise.
  • .add(): Adds the given value to the Set.
  • .delete(): Removes the given value from the Set.
  • .size: Returns the number of values in the Set.

For more information about Sets and their methods in JavaScript, you can check out the MDN documentation.

Conclusion πŸŽ‰

Sets are a powerful and useful data structure in JavaScript, offering a convenient way to store and manipulate unique values. With their useful methods and efficient handling of duplicate values, Sets can be a valuable addition to your JavaScript toolkit.

Top comments (0)