Mastering JavaScript Sets for Efficient Code

Understanding Set in JavaScript Recently, I revisited Set in JavaScript, and it’s one of those small features that can greatly improve performance and code clarity. - What is a Set? A Set is a special JavaScript object that stores unique values only — duplicates are automatically removed. const mySet = new Set(); mySet.add(1); mySet.add(2); mySet.add(2); // duplicate ignored mySet.add(3); console.log(mySet); // Set(3) {1, 2, 3} - Ways to create a Set From scratch → new Set() From an array → perfect for removing duplicates const arr = [1, 2, 2, 3, 4, 4]; const uniqueValues = new Set(arr); - Useful Set Methods add() → Add value has() → Check if value exists (returns true/false) delete() → Remove value clear() → Remove all values size → Get total count const fruits = new Set(["apple", "banana", "mango"]); fruits.has("banana"); // true fruits.delete("banana"); console.log(fruits.size); // 2 - Why use Set? Stores unique values Easily removes duplicates Faster lookup performance Cleaner logic compared to arrays - Performance matters: Set.has() → O(1) Array.includes() → O(n) Small concepts like this can make a big difference when handling large datasets in real-world applications. - To know more, please visit w3schools.com and MDN 😊 #JavaScript #WebDevelopment #FrontendDevelopment #NodeJS #ReactJS #Programming #SoftwareDevelopment #LearningInPublic

  • text

Thanks for putting us on people’s radar 💚

To view or add a comment, sign in

Explore content categories