JavaScript Set Objects
A Set is a collection of unique values.
Each value may occur only once in a Set.
A Set can hold any values of any data type.
How to Create a Set
Create a Set and add existing variables:
Example
// Create some variables
const a = "a";
const b = "b";
const c = "c";
// Create a Set
const letters = new Set();
// Add the values to the Set
letters.add(a);
letters.add(b);
letters.add(c);
Try it Yourself »
Create a Set and add literal values:
Example
// Create a Set
const letters = new Set();
// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Try it Yourself »
Pass an Array to the new Set()
constructor:
For a Set, typeof
returns object:
typeof letters; // Returns object
Try it Yourself »
For a Set, instanceof Set
returns true:
letters instanceof Set; // Returns true
Try it Yourself »
Adding Elements to a Set
If you add equal elements, only the first will be saved:
Example
letters.add("a");
letters.add("b");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
Try it Yourself »
Set Object Methods and Properties
new Set() | Creates a new Set object |
add() | Adds a new element to the Set |
clear() | Removes all elements from a Set |
delete() | Removes an element specified by its value. |
entries() | Returns an array of the values in a Set object |
has() | Returns true if a value exists |
forEach() | Invokes a callback for each element |
keys() | Returns an array of the values in a Set object |
values() | Same as keys() |
size | Returns the element count |