The Set data structure was introduced in ECMAScript 2015, also known as ES6, adding a powerful, new functionality to JavaScript. A Set in JavaScript is a collection of unique values of any type. This means that a Set could include values of type string, number, object, array, etc., and that each value will only occur once within the Set.
Here's an example of a Set in use:
let uniqueValuesSet = new Set();
uniqueValuesSet.add(1);
uniqueValuesSet.add('Hello');
uniqueValuesSet.add([1, 2, 3]);
uniqueValuesSet.add({name: 'John', age: 30});
console.log(uniqueValuesSet);
// Output: Set(4) {1, "Hello", Array(3), {…}}
In this example, we have added four different elements to the Set uniqueValuesSet
. The types of these elements include a number, a string, an array, and an object. No duplicate values are allowed in the Set.
Set comes with a range of methods that allow you to manipulate the contents of the Set. Some of these include add()
, has()
, delete()
, and size
.
let uniqueValuesSet = new Set();
uniqueValuesSet.add(1);
console.log(uniqueValuesSet.has(1));
// Output: true
uniqueValuesSet.delete(1);
console.log(uniqueValuesSet.has(1));
// Output: false
In this example, the has()
method is used to check if a value exists within the Set. If the value exists, has()
will return true
. The delete()
method is used to remove a value from the Set.
Set can be a better alternative to arrays when you want to store unique values. Compared to testing an array for duplicate values, a Set guarantees uniqueness without the need for explicit testing and can be more performance-friendly for large amounts of data.
Remember to utilize the built-in Set data structure the next time your JavaScript project requires the storage of unique values of any kind.