References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Set object

Object JavaScript All modern browsers Updated
Quick answer

A Set is a collection of unique values — adding a duplicate is silently ignored. Create one with new Set(), then use add(value), has(value), delete(value) and size. Its most famous use is deduplicating an array in one line: [...new Set(arr)].

Overview

A Set holds a collection of values where every value is unique. Try to add something that's already there and nothing happens — the set quietly stays as it was. That automatic uniqueness is the whole point, and it makes a Set the natural tool for tracking "have I seen this?" and for removing duplicates.

The API mirrors Map but with values instead of key-value pairs: set.add(value), set.has(value) (a fast membership check), set.delete(value), and the size property. It's iterable, so for...of walks the values in insertion order. Membership testing with has() is faster than Array.includes() on large collections.

The single most common use is the array dedupe: [...new Set(array)] creates a set from the array (dropping duplicates) and spreads it back into a fresh array of unique values. It's the cleanest one-liner in JavaScript for that job. Uniqueness uses the same equality as ===, so objects are compared by reference, not contents.

Syntax

const s = new Set();
s.add(1);
s.add(1);   // ignored - already present
s.add(2);

s.has(1);   // true
s.size;     // 2

// dedupe an array
const unique = [...new Set([1, 1, 2, 3, 3])]; // [1, 2, 3]

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const tags = ['js', 'css', 'js', 'html', 'css', 'js'];

  const unique = [...new Set(tags)];

  document.getElementById('out').textContent =
    'original: ' + tags.length + ' items\n' +
    'unique:   ' + unique.join(', '); // unique: js, css, html
</script>

Best practices

  • Dedupe an array with [...new Set(arr)] — the cleanest one-liner for it.
  • Use a Set for fast membership tests on large collections instead of Array.includes().
  • Track "seen" values while looping to skip repeats.
  • Remember objects are compared by reference, so look-alike objects count as different values.

Frequently asked questions

How do I remove duplicates from an array?
Use a Set: [...new Set(arr)] creates a unique-value array.
What is the difference between a Set and an array?
A Set stores only unique values and has fast has() lookups; an array allows duplicates, keeps full index access and has the rich array methods.
How do I check if a Set contains a value?
Use set.has(value), which returns true or false quickly.
Why doesn't my Set deduplicate objects?
Sets use reference equality for objects, so two separate objects with the same contents are treated as different values.