JavaScript Sets

JavaScript Sets are a collection of unique values, which can be of any type, including primitive values and objects. They are similar to arrays, but have some key differences.

Creating a Set

There are two ways to create a Set in JavaScript:

  • Using the Set constructor:
1let mySet = new Set();
  • Using an array literal:
1let mySet = new Set([1, 2, 3, 4]);

Adding Values to a Set

You can add values to a Set using the add method.

1let mySet = new Set(); 2mySet.add(1); 3mySet.add(2); 4mySet.add(3);

Retrieving Values from a Set

You can retrieve values from a Set using the has method, which returns a Boolean value indicating whether a given value exists in the Set.

1let mySet = new Set([1, 2, 3, 4]); 2console.log(mySet.has(1)); // true 3console.log(mySet.has(5)); // false

Deleting Values from a Set

You can delete values from a Set using the delete method.

1let mySet = new Set([1, 2, 3, 4]); 2mySet.delete(2); 3console.log(mySet); // Set { 1, 3, 4 }

Iterating Over a Set

You can iterate over a Set using a for...of loop, and retrieve both the values and the keys (which are the same in Sets).

1let mySet = new Set([1, 2, 3, 4]); 2for (let value of mySet) { 3 console.log(value); 4} 5 6// Output: 7// 1 8// 2 9// 3 10// 4

Other Built-in Methods

  • clear(): This method removes all elements from a Set.
1let mySet = new Set([1, 2, 3, 4]); 2mySet.clear(); 3console.log(mySet); // Set {}
  • size: This property returns the number of elements in a Set.
1let mySet = new Set([1, 2, 3, 4]); 2console.log(mySet.size); // 4
  • values(): This method returns a new Iterator object that contains the values for each element in the Set, in the order they were inserted.
1let mySet = new Set([1, 2, 3, 4]); 2let values = mySet.values(); 3for (let value of values) { 4 console.log(value); 5} 6 7// Output: 8// 1 9// 2 10// 3 11// 4
  • keys(): This method returns a new Iterator object that contains the values for each element in the Set, in the order they were inserted. It is the same as the values method.
1let mySet = new Set([1, 2, 3, 4]); 2let keys = mySet.keys(); 3for (let key of keys) { 4 console.log(key); 5} 6 7// Output: 8// 1 9// 2 10// 3 11// 4
  • entries(): This method returns a new Iterator object that contains an array of [value, value] for each element in the Set, in the order they were inserted.
1let mySet = new Set([1, 2, 3, 4]); 2let entries = mySet.entries(); 3for (let entry of entries) { 4 console.log(entry); 5} 6 7// Output: 8// [1, 1] 9// [2, 2] 10// [3, 3] 11// [4, 4]
  • forEach(): This method executes a provided function once for each value in the Set.
1let mySet = new Set([1, 2, 3, 4]); 2mySet.forEach(function(value, key) { 3 console.log(value); 4}); 5 6// Output: 7// 1 8// 2 9// 3 10// 4