JavaScript Set()
The Set() constructor creates Set objects.
A Set stores unique values.
Each value can occur only once in a Set.
Syntax
new Set()
new Set(iterable)
Parameters
| Parameter | Description |
|---|---|
| iterable | Optional. An iterable object containing values. |
Return Value
| Call | Returns |
|---|---|
new Set() |
A Set object |
new Set(iterable) |
A Set object initialized with values |
Creating a Set
Example
const letters = new Set();
Creating a Set from an Array
Example
const letters = new Set(["a", "b", "c"]);
Created From Iterables
The Set constructor accepts any iterable object.
Common iterables include:
- Arrays
- Strings
- Maps
- Sets
Unique Values
A Set automatically removes duplicate values.
Example
const letters = new Set(["a", "b", "a", "c", "b"]);
(letters.size) // 3
Value Types
A Set can contain values of any type.
| Value Type | Example |
|---|---|
| String | "John" |
| Number | 123 |
| Boolean | true |
| Object | {} |
| Function | myFunction |
Set vs Array
| Set | Array |
|---|---|
| Unique values only | Duplicates allowed |
Has a size property |
Has a length property |
| No numeric indexes | Indexed elements |
| Designed for value collections | Designed for ordered lists |
Common Properties and Methods
sizeadd()has()delete()clear()keys()values()entries()forEach()
Iterable Information
Set objects are iterable.
A Set can be used in:
for...ofloopsArray.from()new Set(iterable)- Spread syntax (
...)
Example
const letters = new Set(["a", "b", "c"]);
const arr = [...letters];
Object Hierarchy
Set objects inherit from Object.
Object └─ Set
| What | Value |
|---|---|
| Constructor Type | Function |
| Creates | Set objects |
| Inherits From | Object |
| Iterable | Yes |
Set objects store unique values only.
Adding an existing value does not create a duplicate.
Browser Support
new Set() is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers since June 2017:
| Chrome 51 |
Edge 15 |
Firefox 54 |
Safari 10 |
Opera 38 |
| May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |