Ad space (banner)
🟨JavaScript Lessons
Lesson 28 / 69

Using Set (Collections)

In this lesson you'll use JavaScript's Set (a collection) so you can manage data without duplicates and check for membership quickly. This is for people searching "JavaScript Set usage" or "JavaScript array remove duplicates."

A Set is a "no-duplicates box" that can't hold the same value twice. It's handy when you want to strip duplicates out of an array, or quickly check whether a value is contained. There's also a performance benefit — Set.has() runs faster than an array's .includes() when there's a lot of data. It's a mechanism that lets you handle the mathematical idea of a "set" directly in your program.

The sample code builds a duplicate-free uniqueNums from an array nums that contains duplicates, using new Set(nums), then converts it back to an array with the spread syntax [...uniqueNums] and displays it. There's also a method like .has(2) for checking whether a particular value is contained. This produces shorter, more readable code than writing a duplicate check with a for loop.

A common beginner stumbling block is that, unlike an array, a Set can't be accessed by an index number. A statement like uniqueNums[0] won't work — to pull out values you either need to convert it to an array or process it one at a time with for...of. Depending on the situation, you'll end up going back and forth between arrays and Sets.

In real development, Set is used widely in situations that need duplicate management or fast existence checks — removing duplicate tags selected in a form, or recording visited page IDs to check for repeats.

Beyond what's shown here, Set also has methods like .delete(value) for removing a specific value, and a .size property for checking the number of elements — the counterpart to an array's .length.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)