JavaScript: All Set Methods

RustcodeWeb
2 min readSep 7, 2024

--

Photo by Lavi Perchik on Unsplash

The Set object in JavaScript allows you to store unique values of any type, whether primitive values or object references. It automatically handles duplicates, ensuring each value in the set is unique. This article covers some of the essential methods available for the Set object.

All Methods and Properties:

Here are some commonly used methods of the Set object:

// Create a new Set
const set = new Set();

// 1. add(value): Adding values
set.add('apple');
set.add('banana');
set.add('cherry');
set.add('apple'); // Duplicate value will not be added
console.log(set); // Output: Set { 'apple', 'banana', 'cherry' }

// 2. delete(value): Removing a value
set.delete('banana');
console.log(set); // Output: Set { 'apple', 'cherry' }

// 3. has(value): Checking for a value
console.log(set.has('apple')); // Output: true
console.log(set.has('banana')); // Output: false

// 4. clear(): Removing all values
set.clear();
console.log(set); // Output: Set {}

// 5. size: Checking the number of elements in the set
set.add('apple');
set.add('banana');
console.log(set.size); // Output: 2

// 6. forEach(callbackFn): Iterating over set values
set.forEach(value => {
console.log(value);
});
// Output:
// apple
// banana

// 7. values(): Getting an iterator of all values
const valuesIterator = set.values();
console.log(valuesIterator.next().value); // Output: apple
console.log(valuesIterator.next().value); // Output: banana

// 8. entries(): Getting an iterator of [value, value] pairs
const entriesIterator = set.entries();
console.log(entriesIterator.next().value); // Output: [ 'apple', 'apple' ]
console.log(entriesIterator.next().value); // Output: [ 'banana', 'banana' ]

// 9. keys(): Getting an iterator of keys (same as values for Set)
const keysIterator = set.keys();
console.log(keysIterator.next().value); // Output: apple
console.log(keysIterator.next().value); // Output: banana

Support Our Work: BuyMeACoffee

Originally published at https://www.rustcodeweb.com on September 7, 2024.

--

--

No responses yet