DEV Community

Cover image for Javascript - Basics of using built-in Set method
Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Javascript - Basics of using built-in Set method

JavaScript Set - Concise Notes šŸš€

šŸ”¹ What is a Set?

A Set is a built-in JavaScript object that stores unique values (no duplicates).

šŸ”¹ Creating a Set

const mySet = new Set([1, 2, 3, 4, 5]);
Enter fullscreen mode Exit fullscreen mode

šŸ”¹ Key Methods

Method Description Example Usage
.add(value) Adds a value to the Set mySet.add(6);
.delete(value) Removes a value mySet.delete(3);
.has(value) Checks if value exists mySet.has(2); // true
.clear() Removes all elements mySet.clear();
.size Returns the number of elements mySet.size; // 5

šŸ”¹ Iterating Over a Set

mySet.forEach(value => console.log(value)); // Loop using forEach
for (let value of mySet) console.log(value); // Loop using for...of
Enter fullscreen mode Exit fullscreen mode

šŸ”¹ Convert Set to Array

const numArray = [...mySet];
Enter fullscreen mode Exit fullscreen mode

šŸ”¹ Convert Array to Set (Remove Duplicates)

const uniqueNums = new Set([1, 2, 2, 3, 4]); // {1, 2, 3, 4}
Enter fullscreen mode Exit fullscreen mode

šŸ”¹ When to Use a Set?

āœ… Fast lookups (O(1))

āœ… Removing duplicates

āœ… Tracking unique values

šŸš€ Best for performance when working with unique data!

Top comments (0)