Understanding JavaScript Set Methods
JavaScript Set Methods Overview of Set Methods and Properties new Set() add() clear() delete() entries() forEach() has() keys() values() size The new Set() Method You can create...
JavaScript Set Methods
Overview of Set Methods and Properties
- new Set()
- add()
- clear()
- delete()
- entries()
- forEach()
- has()
- keys()
- values()
- size
The new Set() Method
You can create a new set by passing an array to the new Set() constructor. This allows for the initialization of a set with a collection of elements.
The add() Method
When using the add() method, only unique values are stored in a set. If you attempt to add a duplicate element, the existing set remains unchanged as it does not save multiple instances of the same value.
The size Property
The size property returns the number of unique elements within a set.
Listing Set Elements
To list all elements in a set, you can use a for..of loop, which iterates over each value.
The has() Method
The has() method checks for the existence of a specified value within a set, returning true if the value is found.
The forEach() Method
The forEach() method executes a provided function once for each value contained in the set.
The values() Method
The values() method provides an Iterator object, which allows access to all the values stored in a set.
The keys() Method
In sets, the keys() method returns an Iterator object with the set's values. Since sets do not have keys, this method functions identically to values().
The entries() Method
The entries() method returns an Iterator containing [value, value] pairs. Though traditionally designed to return [key, value] pairs, in sets, both elements are identical, aligning their behavior with maps.
Learn More
For further reading, explore additional topics such as JavaScript Sets, Set Logic, Weak Sets, Set Reference, and JavaScript Maps.