JavaScript Set: Unique Values and Membership
Quick answer
Set stores unique values in insertion order. It is useful when membership matters more than assigning a separate value to each key.
How it works
Use new Set(iterable), add(value), has(value), delete(value) and clear(). Adding an existing value does not create another entry or move it. size counts distinct members. Spread creates an array of members; objects remain distinct by identity.
const s = new Set([3,1,3,2]); console.log(JSON.stringify([...s]));Expected output in Node.js:
[3,1,2]Duplicates disappear without sorting.
const s = new Set(["x", "y"]); s.add("x"); s.delete("x"); s.add("x"); console.log(JSON.stringify([...s]));Expected output in Node.js:
["y","x"]Deletion and reinsertion put x at the end.
Common mistakes
A Set is not sorted automatically and does not perform deep deduplication of objects.
Practice
Return the distinct labels of an array in first-occurrence order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Set: Unique Values and Membership — Knowledge Check
Apply the taught concept and predict the output.
What determines the order of ordinary Set iteration?
What happens if the same object is added twice to a Set?
What does Set.prototype.delete report?
What is the exact console output in JavaScript Set: Unique Values and Membership example 1?
const s = new Set([3,1,3,2]); console.log(JSON.stringify([...s]));What is the exact console output in JavaScript Set: Unique Values and Membership example 2?
const s = new Set(["x", "y"]); s.add("x"); s.delete("x"); s.add("x"); console.log(JSON.stringify([...s]));