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!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay