JavaScript Set Reference
A JavaScript Set is a collection of unique values.
Each value can only occur once in a Set.
The values can be of any type, primitive values or objects.
How to Create a Set
You can create a JavaScript Set by:
- Passing an Array to
new Set()
- Create a Set and use
add()
to add values
Example 1
Pass an Array to the new Set()
constructor:
// Create a Set
const letters = new Set(["a","b","c"]);
Try it Yourself »
Example 2
Create a Set and add values:
// Create a Set
const letters = new Set();
// Add Values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Try it Yourself »
JavaScript Set Methods and Properties
Method | Description |
---|---|
new Set() | Creates a new Set |
add() | Adds a new element to the Set |
clear() | Removes all elements from a Set |
delete() | Removes an element from a Set |
entries() | Returns an Iterator with the [value,value] pairs from a Set |
forEach() | Invokes a callback for each element |
has() | Returns true if a value exists |
keys() | Same as values() |
values() | Returns an Iterator with the values in a Set |
Sets have only one property:
Property | Description |
---|---|
size | Returns the number of elements in a Set |
The new Set() Method
Pass an Array to the new Set()
constructor:
Listing Set Elements
You can list all Set elements (values) with a for..of loop:
Example
// Create a Set
const letters = new Set(["a","b","c"]);
// List all Elements
let text = "";
for (const x of letters) {
text += x;
}
Try it Yourself »