The JavaScript Set class
Let's dive into the native Set class introduced in ECMAScript 2015 (ES6) and explore how to use it effectively.
The Set class provides a built-in, efficient way to work with sets in JavaScript. It offers all the fundamental set operations and is optimized for performance.
Now, let's look at the methods and features available in the native Set class:
- Two constructors:
new Set()
: creates an empty Set.new Set(iterable)
: creates a Set from an iterable object (for example, an array).
add(value)
: adds a value to the set (if it is not already present). Returns the Set object itself for chaining.delete(value)
: removes the specified value from the set. Returnstrue
if the value was present and removed, otherwisefalse
.clear()
: removes all elements from the set.has(value)
: returnstrue
if the value exists in the set, otherwisefalse
.- Different methods for iterating the set:
forEach(callbackFn)
: executes the providedcallbackFn
for each value in the set...