JavaScript Course
JavaScript
/
Intermediate

Set Deep Dive

Definition

The Set object lets you store unique values of any type, whether primitive values or object references.

Explain Like I'm New

A Set is exactly like an Array, but it has a built-in bouncer that refuses to let duplicates in. If you try to add the number 5, and 5 is already in the Set, the Set just silently ignores you.

Real World Example

You have an array of 1,000 tags added to posts, and you want to extract just the unique tags to create a filter menu. `const uniqueTags = [...new Set(allTags)]`.

Common Use Cases

  • •Removing duplicates from arrays
  • •Fast O(1) lookups to check if an item exists

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • How do you remove duplicate numbers from an array using a Set?

intermediate

  • Why is `set.has(val)` faster than `array.includes(val)`?

advanced

  • If you add two identical objects to a Set, will it reject the second one?

Flash Cards

Question

Why is set.has() faster?

Click to reveal answer
Answer

`array.includes` is an O(N) operation. It has to loop through every single item in the array to find what you want. A Set is backed by a hash table. Checking if an item exists is an O(1) operation—instant, no matter how big the Set is.

Question

Will it reject two identical objects?

Click to reveal answer
Answer

No! `{a: 1}` and `{a: 1}` are two different objects pointing to two different memory locations. Since Sets check equality by reference (not by shape), it sees them as completely unique items and allows both.