➥ JS Tutorial
- JS HOME
- JS introduction
- JS Where to
- JS Output
- JS Statements
- JS Syntax
- JS Variables
- JS Operators
- JS Assignment
- JS Data Types
- JS Functions
- JS Objects
- JS Events
- JS Sting methods
- JS String Search
- JS Arrays Methods
- JS Arrays
- JS Sorting Arrays
- JS Array Iteration
- JS Math Object
- JS Comparison & Logical Operators
- JS if else and else if
- JS Switch Statement
- JS For Loop
- JS For In
- JS For Of
- JS While Loop
- JavaScript Break
- JS Sets
- JavaScript typeof
- JS Type Conversion
- JS Bitwise Operations
- JS JSON
- JS Best Practices
- JS Reserved Words
- JS Number Methods
➥ JS Objects
➥ JS Functions
➥ JS Classes
➥ JS HTML DOM
- JavaScript HTML DOM
- JS HTML DOM Document
- JS HTML DOM Elements
- Changing HTML
- JS Forms
- JS HTML DOM - CSS
- DOM Events
- HTML DOM Event Listener
➥ JS Browser BOM
➥ JS Web APIs
➥ JS AJAX
➥ JS JSON
Tutorial
JavaScript Sets
A JavaScript Set is a collection of unique values.
Each value can only occur once in a Set.
Essential Set Methods
Method | Description |
---|---|
new Set() | Creates a new Set |
add() | Adds a new element to the Set |
delete() | Removes an element from a Set |
has() | Returns true if a value exists in the Set |
forEach() | Invokes a callback for each element in the Set |
values() | Returns an iterator with all the values in a Set |
Property | Description |
size | Returns the number of elements in a Set |
How to Create a Set
You can create a JavaScript Set by:
• Passing an Array to new Set()
• Create a new Set and use add() to add values
• Create a new Set and use add() to add variables
The new Set() Method
Pass an Array to the new Set()
constructor:
Example:
// Create a Set
const letters = new Set(["a","b","c"]);
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");
Create a Set and add variables:
EXAMPLE ❯
The add() Method
If you add equal elements, only the first will be saved:
EXAMPLE ❯
The forEach() Method
The forEach()
method invokes (calls) a function for each Set element:
EXAMPLE ❯
The values() Method
The values()
method returns a new iterator object containing all the values in a Set:
Example:
letters.values() // Returns [object Set Iterator]
Now you can use the Iterator object to access the elements: