Course contentsShow
← JavaScript
Lesson 1044 of 2,72324. Maps and SetsFree lesson

What is a Set?

Learn how Sets store unique values and differ from arrays for membership testing.

What is a Set?

You'll learn what a Set is in JavaScript and how it differs from arrays for storing unique values.

Understanding Sets

A Set is a built-in JavaScript collection that stores unique values. Unlike arrays, which can contain duplicates, a Set automatically ensures every value appears only once. Think of it like a bag of marbles where you can't accidentally put in two identical marbles—the bag simply won't accept duplicates.

Why Sets Matter

Arrays are great for ordered lists, but when you need to guarantee uniqueness or quickly check if something exists, Sets shine. If you try adding the same value multiple times to a Set, it will only keep one copy.

How Sets Differ from Arrays

With arrays, you can have [1, 2, 2, 3] where 2 appears twice. With a Set, if you add 1, then 2, then 2 again, then 3, you'll end up with just {1, 2, 3}. The duplicate 2 is ignored.

Membership testing (checking if a value exists) is also more efficient with Sets than arrays. Instead of searching through every element like arrays do, Sets can check existence much faster—especially important with large collections.

When to Choose Sets

Use a Set when:

  • You need to eliminate duplicates from a collection
  • You frequently check if a value exists
  • Order doesn't matter as much as uniqueness

Use an array when:

  • You need duplicate values
  • Index-based access is important
  • Order matters for your logic

Key Takeaway: A Set is a collection that stores only unique values, making it ideal for membership testing and automatically removing duplicates—unlike arrays which allow repeated values.