Mastering Set in JavaScript Set in JavaScript allows us to store unique values only. Arrays can do something similar but there are important differences we should know. In this post, we’ll explore how Set works and when to use it. For the full comparison with Array, please watch the video. A Set is an unordered collection that stores only unique values and is optimised for quick existence checks. 🔹 Create a Set const mySet = new Set([1,2,3]); 🔹 Add values mySet.add(4); If we try to add a duplicate value: mySet.add(3); it will be ignored, because a Set only stores unique values. We can also add strings, arrays, and objects in the same way. In the case of objects though, a Set treats values as duplicates if they share the same reference. const a = {id: 1}; mySet.add(a); mySet.add(a); 🔹 Finding values Unlike arrays, Sets don’t have indexes, so values can’t be accessed by position. Instead, values are accessed through iteration using forEach or for...of: mySet.forEach((value) => console.log(value)); or for (const value of mySet) { console.log(value); } There is no index available during iteration. 🔹 Remove or clear values: mySet.delete(2); mySet.clear(); 🔹 Check for value: mySet.has(2); 🔹 Get size: mySet.size; Use a Set when we need to track only unique values and want fast checks to see if something already exists. #frontend #javascript #set #array

Clear and practical explanation. Sets are often overlooked, but they’re perfect for uniqueness and fast existence checks without extra logic. Understanding when to choose Set over Array is one of those small fundamentals that makes code cleaner and more intentional.

Valentin Soare

Full-Stack Developer (Kotlin/Java) & DevOps Engineer @ LSEG (London Stock Exchange Group) | Oracle Java Certified | HashiCorp Terraform & 2x AWS Certified

4mo

this really highlights why sets are so powerful for uniqueness validation. the reference-based handling you mentioned is exactly what makes them shine in those specific scenarios.

Like
Reply

On-device inference is quietly becoming a UX advantage, not just a privacy one. Zero network roundtrips changes what ‘real-time’ actually feels like.

Like
Reply

Wow, that was awesome 😃 I didn't know JavaScript had something like this. It's really useful, though a bit tricky 😁

Like
Reply

Thanks for this. Run throughs like this are really helpful. Helps me resort the stack of options I might reach for in one scenario or another.

Like
Reply

Easy to follow. I really like the marking and the use of arrows. Makes it easy to follow along.

Like
Reply

Great Explanation of an often overlooked feature in JavaScript. Keep up the good work.

Like
Reply

Nice and simple explanation! Easy to read, practical examples when using a Set.

Like
Reply

Best explanation ever

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories