Just like an array, a set is used for storing multiple elements, however, the elements in a set must be unique. The elements can be of any data type such as strings, numbers, objects, etc.
How to create a JavaScript Set
The new set()
constructor function is used to create a set in JavaScript.
let mySet = new Set();
The set can be populated with values by adding an array of elements to the set. Duplicate elements in a set are ignored.
let mySet = new Set([1, "a", true, {name: "John Smith"}]);
Adding New Elements to a Set
The add()
method can be used to add new elements to a set.
let mySet = new Set([1, 2, 3, 4, 5]);
mySet.add(6)
Accessing Set Elements
The values()
method can be used to access the elements in a set. The values()
method returns a new iterator object containing all elements in the set. Each element in the set can be assessed by looping through the iterator object.
let mySet = new Set([1, 2, 3, 4, 5]);
let setValues = mySet.values();
for(let i of setValues){
console.log(i);
}
The has()
method can be used to check if a specific element is available in a set. The has()
method returns a boolean value indicating the availability of the element.
let mySet = new Set([1, 2, 3, 4, 5]);
console.log(mySet.has(4)); // true
Removing Set Elements
The delete()
and the clear()
methods can be used to remove elements from a set.
The clear()
removes all elements from a set.
let mySet = new Set([1, 2, 3, 4, 5]);
mySet.clear();
The delete()
method removes a specific element from a set.
let mySet = new Set([1, 2, 3, 4, 5]);
mySet.delete(2);
Iterating through a Set
You can iterate through a set using the for...of
loop or the foreach()
method. The elements are accessed in the order in which they were inserted into the set.
Using the for...of
loop
let mySet = new Set([1, 2, 3, 4, 5]);
for (let value of mySet.values()){
console.log(value);
}
Using the foreach()
method
let mySet = new Set([1, 2, 3, 4, 5]);
mySet.forEach(function(value) {
console.log(value);
});
JavaScript WeakSet
Unlike a set that can contain any data type, a weakset can only contain objects. A weakset throws an error when any other data type apart from an object is being added.
let myWeakSet = new WeakSet();
let phone = {
make: 'Samsung',
color: 'black'
}
myWeakSet.add(phone);
let output = myWeakSet.has(phone);
console.log(output);
Note: WeakSets are not iterable