The JavaScript ES6 has introduced two new data structures, i.e Set and WeakSet.
Set is similar to an array that allows us to store multiple items like numbers, strings, objects, etc. However, unlike an array, a set cannot contain duplicate values.
Create JavaScript Set
To create a Set, you need to use the new Set() constructor. For example,
When duplicate values are passed to a Set object, the duplicate values are excluded.
Access Set Elements
You can access Set elements using the values() method and check if there is an element inside Set using has() method. For example,
You can use the has() method to check if the element is in a Set. For example,
Adding New Elements
You can add elements to a Set using the add() method. For example,
Output
Set Iterator [1, 2] Set Iterator [1, 2, 3] Set Iterator [1, 2, 3]
Removing Elements
You can use the clear() and the delete() method to remove elements from a Set.
The delete() method removes a specific element from a Set. For example,
The clear() method removes all elements from a Set. For example,
Iterate Sets
You can iterate through the Set elements using the for...of loop or forEach() method. The elements are accessed in the insertion order. For example,
Output
1 2 3
JavaScript WeakSet
The WeakSet is similar to a Set. However, WeakSet can only contain objects whereas a Set can contain any data types such as strings, numbers, objects, etc. For example,
When you try to add other data types besides objects, WeakSet throws an error. For example,
WeakSet Methods
WeakSets have methods add(), delete(), and has(). For example,
WeakSets Are Not iterable
Unlike Sets, WeakSets are not iterable. For example,
Mathematical Set Operations
In JavaScript, Set does not provide built-in methods for performing mathematical operations such as union, intersection, difference, etc. However, we can create programs to perform those operations.
Example: Set Union Operation
Output
Set {"apple", "mango", "orange", "grapes", "banana"}
Example: Set Intersection Operation
Output
Set {"apple"}
Example: Set Difference Operation
Output
Set {"mango", "orange"}
Example: Set Subset Operation
Output
true
JavaScript Sets and WeakSets were introduced in ES6. Some browsers may not support their use. To learn more, visit JavaScript Sets support and JavaScript WeakSets support.