Skip to content

Mastering JavaScript ES6 Set: The Secret Weapon for Unique Values

Learn everything about JavaScript ES6 Set with examples. Discover its features, how to remove duplicates, and perform set operations easily.

Dasun Kalupahana 1 min read 523 views 0 comments

When working with collections in JavaScript, arrays are often the go-to data structure. However, ES6 introduced a new built-in object called Set, which makes handling unique values much easier and more efficient.

In this article, we’ll explore the key features of Set and demonstrate them with practical examples.

🔹 What is a Set?

A Set in JavaScript is a collection of unique values.

  • It can store any type of data (primitive or object references).
  • Duplicate values are automatically removed.
const mySet = new Set([1, 2, 3, 3, 4, 5]);
console.log(mySet); // Output: Set(5) {1, 2, 3, 4, 5}

Notice how the duplicate 3 was removed automatically.


🔹 Creating a Set

You can create a set using the Set constructor:

const emptySet = new Set(); // Empty set
const numberSet = new Set([1, 2, 3, 4]); // Set with initial values

console.log(emptySet.size);  // 0
console.log(numberSet.size); // 4

 

🔹 Adding Values

Use .add() to insert values into a set.

const fruits = new Set();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // Duplicate, won’t be added

console.log(fruits); // Set(2) {"Apple", "Banana"}

 

🔹 Checking Values

Use .has() to check if a value exists

console.log(fruits.has("Apple"));  // true
console.log(fruits.has("Mango"));  // false

🔹 Deleting Values

Use .delete() to remove a specific value and .clear() to remove all.

fruits.delete("Banana");
console.log(fruits); // Set(1) {"Apple"}

fruits.clear();
console.log(fruits); // Set(0) {}

🔹 Iterating Over a Set

You can loop through a set using for...of or forEach().

const colors = new Set(["Red", "Green", "Blue"]);

// Using for...of
for (let color of colors) {
  console.log(color);
}

// Using forEach
colors.forEach(color => console.log(color));

🔹 Converting Between Set and Array

Since Set doesn’t allow duplicates, it’s useful for removing duplicates from arrays.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

You can also convert a Set back to an array:

const mySet = new Set(["A", "B", "C"]);
const myArray = Array.from(mySet);

console.log(myArray); // ["A", "B", "C"]

🔹 Useful Applications of Set

  • Remove duplicates from arrays
  • Check existence of items quickly
  • Perform set operations like union, intersection, and difference

Example: Union, Intersection, Difference

const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);

// Union
const union = new Set([...setA, ...setB]);
console.log(union); // Set(6) {1, 2, 3, 4, 5, 6}

// Intersection
const intersection = new Set([...setA].filter(x => setB.has(x)));
console.log(intersection); // Set(2) {3, 4}

// Difference
const difference = new Set([...setA].filter(x => !setB.has(x)));
console.log(difference); // Set(2) {1, 2}

 


Conclusion

The ES6 Set is a powerful and efficient data structure for handling unique values in JavaScript.

  • No duplicates allowed
  • Fast lookups with .has()
  • Easy conversion to/from arrays
  • Perfect for set operations

By using Set, you can write cleaner and more optimized code, especially when working with collections that require uniqueness.

If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel! 🧱✨

Free tools for this topic

Code snippets and fixes for this topic

Get one practical tip every week

New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.

Have a question about this post?

Ask the community: other developers and the author can answer.

Ask the community

Get notified about new articles

One click, no email needed. Turn it off anytime with the bell at the top.

Get new articles on your iPhone

Add DEV Talk to your Home Screen, open it, then tap the bell.

Rate this post
0.0
Share

Enjoying the content?

If this article helped you, you can support the author with a coffee. It keeps new posts coming.

Buy me a coffee (opens in a new tab)

Comments 0

Be kind. Comments with links are reviewed before they appear.

No comments yet

Be the first to share your thoughts.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.