In JavaScript, Set is a built-in object that allows you to store unique values of any type, whether primitive values or object references. The Set object was introduced in ECMAScript 2015 (ES6) and provides a simple and efficient way to manage a collection of unique values.
Here's a brief explanation of Set:
-
Unique Values:
- A
Setcan only contain unique values. If you try to add a duplicate value, it won't be added, and the set will remain unchanged.
- A
-
Creation:
- You can create a new
Setusing thenew Set()constructor. You can also initialize aSetwith an iterable, such as an array.
const mySet = new Set();or
const mySet = new Set([1, 2, 3, 4, 5]); - You can create a new
-
Adding and Removing Elements:
- You can add an element to a
Setusing theaddmethod:
mySet.add(6); - You can add an element to a
-
To remove an element, you can use the
deletemethod:
mySet.delete(3);
-
Checking for Existence:
- You can check if a value exists in a
Setusing thehasmethod:
console.log(mySet.has(3)); // Returns false after deleting 3 - You can check if a value exists in a
-
Size:
- The
sizeproperty returns the number of elements in aSet:
console.log(mySet.size); // Returns the number of elements - The
-
Iteration:
- You can iterate through the elements of a
Setusing methods likeforEachor thefor...ofloop:
mySet.forEach(value => { console.log(value); });or
for (const value of mySet) { console.log(value); } - You can iterate through the elements of a
-
Clearing the Set:
- The
clearmethod removes all elements from theSet:
mySet.clear(); - The
Set is particularly useful when you need to maintain a collection of unique values without duplicates. It provides a convenient and performant way to handle such scenarios.
Support My Work ❤️
If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!
Connect with Me 🌍
Let’s stay connected! You can follow me or reach out on these platforms:
🔹 YouTube – Tutorials, insights & tech content
🔹 LinkedIn – Professional updates & networking
🔹 GitHub – My open-source projects & contributions
🔹 Instagram – Behind-the-scenes & personal updates
🔹 X (formerly Twitter) – Quick thoughts & tech discussions
I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!
Disclaimer
This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.
Top comments (0)