JavaScript Set

JavaScript Sets are collections of unique values. They are a new data structure introduced in ES6 that can be used to store and manipulate data. Sets are similar to arrays, but they don't allow duplicate values.

Why should you use it?

  • Sets are more efficient than arrays when it comes to searching for values.
  • They make it easier to check for the existence of a value in a collection.
  • They allow you to perform set operations such as union and intersection.

Set

A Set is a collection of unique values. It can store any type of values including primitive values, objects, and functions. A Set is an iterable object, meaning it can be used in a for...of loop.

script.js
const set = new Set([1, 2, 3, 4]);
console.log(set);

The Set constructor takes an iterable object as an argument and creates a new Set object. We can also create an empty Set object using the new keyword.

script.js
const set = new Set();
console.log(set);

We can add values to a Set using the add() method. The add() method returns the Set object, so we can chain multiple add() calls together.

script.js
const set = new Set();
set.add(1).add(2).add(3);
console.log(set);

We can check if a Set contains a value using the has() method. The has() method returns a boolean value.

script.js
const set = new Set([1, 2, 3]);
console.log(set.has(1));
console.log(set.has(4));

We can remove a value from a Set using the delete() method. The delete() method returns a boolean value.

script.js
const set = new Set([1, 2, 3]);
console.log(set.delete(1));
console.log(set.delete(4));
console.log(set);

We can convert a Set to an array using the Array.from() method. The Array.from() method takes an iterable object as an argument and returns an array.

script.js
const set = new Set([1, 2, 3]);
const array = Array.from(set);
console.log(array);

We can loop over a Set using a for...of loop. The for...of loop iterates over the values in the Set.

script.js
const set = new Set([1, 2, 3]);
for (const value of set) {
  console.log(value);
}