Set Object
The Set object in JavaScript is a collection of unique values, meaning a value can only occur once in a Set. It maintains the order of insertion and allows for any type of value, whether primitive or object references.
- Creation:
const set = new Set();creates an empty set. - Adding Values:
set.add(value);adds a new value to the set. - Checking Existence:
set.has(value);returnstrueif the value exists in the set. - Removing Values:
set.delete(value);removes the value from the set. - Size:
set.size;returns the number of values in the set. - Iteration: The
Setobject can be iterated over using methods likeforEach, or usingfor...ofloops onset.keys(),set.values(), andset.entries().
Example Usage
const set = new Set();
set.add('apple');
set.add('banana');
set.add('apple'); // Duplicate, will not be added
console.log(set.has('apple')); // Output: true
console.log(set.size); // Output: 2
set.delete('banana');
console.log(set.size); // Output: 1
set.forEach(value => {
console.log(value);
});
// Output:
// apple
Additional Information
Maintaining Order:
- Sets maintain the order of insertion, which makes iteration predictable.
Value Types:
- Values in a
Setcan be of any type, including objects, functions, and primitives.
- Values in a
Iteration:
- You can iterate over the values in a
Setusing methods likefor...ofwithset.values()orset.keys()(which are identical in sets).
- You can iterate over the values in a