0
0
JavascriptConceptBeginner · 3 min read

What is Set in JavaScript: Explanation and Examples

Set in JavaScript is a built-in object that stores unique values of any type, meaning it automatically removes duplicates. It works like a collection where each value can only appear once, making it useful for managing lists without repeats.
⚙️

How It Works

A Set in JavaScript is like a special box where you can put items, but it will never allow two identical items inside. Imagine you have a basket for collecting unique fruits. If you try to add the same fruit twice, the basket will only keep one of them.

Under the hood, the Set keeps track of each value you add and checks if it already exists before adding it. This makes it very efficient for removing duplicates automatically without extra work.

💻

Example

This example shows how to create a Set, add values, and see that duplicates are ignored.

javascript
const fruits = new Set();
fruits.add('apple');
fruits.add('banana');
fruits.add('apple'); // duplicate
console.log(fruits);
console.log(fruits.has('banana'));
console.log(fruits.size);
Output
Set { 'apple', 'banana' } true 2
🎯

When to Use

Use a Set when you need to store a list of items but want to avoid duplicates automatically. For example, if you collect user IDs from different sources and want to ensure each ID appears only once, a Set is perfect.

It is also useful when you want to quickly check if an item exists in a collection, as Set provides fast lookup with the has() method.

Key Points

  • Stores unique values: No duplicates allowed.
  • Any value type: Can store strings, numbers, objects, etc.
  • Fast lookup: Use has() to check presence quickly.
  • Iterable: Can loop through values with for...of.

Key Takeaways

A Set stores only unique values, automatically removing duplicates.
Use Set to manage collections where uniqueness matters, like user IDs or tags.
Sets support any data type and provide fast checks with the has() method.
You can loop through a Set easily using for...of loops.