Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 156 ยท Arrays

Sets

Learn JavaScript Sets - store unique values, add, check and delete items, loop in order, and combine sets with union, intersection and difference.

An array happily stores the same value twice. Often that is exactly what you want, but sometimes it is a bug waiting to happen: a tag added twice, a user counted twice, a page visited twice. A Set is a collection that stores each value only once. Adding something that is already there simply does nothing.

Sets also answer "is this value in the collection?" very quickly, no matter how large the collection grows. In this lesson you will learn the Set API, how sets decide that two values are "the same", how to convert between sets and arrays, and how to combine sets with operations such as union and intersection, including the newer built-in methods.

Creating a set and adding values

Create an empty set with new Set(), or pass any iterable (an array, a string, another set) to fill it. Duplicates in the input are dropped:

JavaScript
const empty = new Set();
const colors = new Set(["red", "green", "red", "blue"]); // 3 values
const letters = new Set("banana");                       // "b", "a", "n"

The core API is small:

Member What it does
set.add(value) Adds a value (if it is new) and returns the set, so calls can be chained
set.has(value) true if the value is in the set
set.delete(value) Removes a value; returns true if it was there
set.size How many values the set holds (a property, not a method)
set.clear() Removes everything
JS The Set basics

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Sets have no indexes. There is no tags[0] and no tags.at(-1). A set is about membership ("is it in there?"), not position. If you need positions, convert to an array first.

When are two values "the same"?

A set uses an algorithm called SameValueZero to decide whether a value is already present. In practice it behaves like ===, with one friendly difference:

  • 1 and "1" are different (different types).
  • NaN is equal to NaN, so a set stores it only once. (With ===, NaN is not even equal to itself.)
  • 0 and -0 count as the same value.
  • Objects are compared by reference: two objects with identical contents are still two different values.
JS How a Set compares values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If you need to deduplicate objects by their contents, store a key instead, such as an id or a string like `${x},${y}`, or use a Map keyed by id.

Looping over a set

Sets remember insertion order. Values come out in the order they were first added, and re-adding an existing value does not move it. You can loop with for...of, with forEach, or turn the set into an array:

JS Iterating and converting

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Sets also have keys(), values() and entries(), mostly so they look like Maps. For a set, keys() and values() give the same values, and entries() gives [value, value] pairs. You will rarely need them.

Why sets are fast

Checking array.includes(x) means looking at items one by one until it finds a match, so the work grows with the length of the array. set.has(x) uses a hash table internally and takes roughly the same time whether the set holds ten values or ten million.

That matters inside loops. This code checks every order against a list of blocked customers:

JavaScript
// Slow for big lists: includes() scans the whole array each time
const flagged = orders.filter((o) => blockedIds.includes(o.customerId));

// Fast: build the set once, then each has() is a quick lookup
const blocked = new Set(blockedIds);
const flaggedFast = orders.filter((o) => blocked.has(o.customerId));

For a dozen items, the difference is invisible. For thousands of orders and thousands of ids, it is the difference between instant and noticeably slow.

Set operations

Mathematics has names for the common ways to combine two sets, and they map directly to everyday questions:

Operation Question it answers Example result for A = {1, 2, 3}, B = {2, 3, 4}
Union What is in A or B? {1, 2, 3, 4}
Intersection What is in both? {2, 3}
Difference (A โˆ’ B) What is in A but not B? {1}
Symmetric difference What is in exactly one of them? {1, 4}
Subset Is everything in A also in B? false
Disjoint Do they share nothing? false

The built-in methods

Modern JavaScript has a method for each of these. The first four return a new set; the last three return a boolean. None of them changes the original sets.

JavaScript
a.union(b);
a.intersection(b);
a.difference(b);
a.symmetricDifference(b);
a.isSubsetOf(b);
a.isSupersetOf(b);
a.isDisjointFrom(b);
JS The new Set methods

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Support: union(), intersection(), difference(), symmetricDifference(), isSubsetOf(), isSupersetOf() and isDisjointFrom() were standardized in ES2025. They work in Chrome and Edge 122+, Firefox 127+, Safari 17+ and Node.js 22+. Older browsers and Node versions don't have them, which is why the example checks first. The fallbacks below work everywhere.

The argument must be set-like: an object with a size, a has() method and a keys() method, such as a Set or a Map. A plain array is not accepted and throws a TypeError, so wrap it first: a.union(new Set(array)).

Fallbacks with spread and filter

Every operation is a short expression with spread and filter, and these versions run in any environment that supports Set:

JS Set operations without the new methods

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that each fallback uses has() on a set inside the loop. That is the speed trick from the previous section.

Practical uses

A few patterns where a set is the natural choice:

  • Toggling a selection. Keep the ids of selected rows in a set: selected.has(id) ? selected.delete(id) : selected.add(id). No duplicates, no searching.
  • Tracking what you have already seen, for example while walking a graph or a tree that may contain loops. You will meet this in recursion.
  • Checking permissions or allowed values: const allowed = new Set(["png", "jpg", "webp"]); allowed.has(extension).
  • Comparing two lists: which tags were added, which were removed? That is two difference calls.

A quick word on WeakSet

A WeakSet is a set that only holds objects and holds them "weakly": if nothing else in your program refers to an object, the garbage collector may remove it, and it silently disappears from the WeakSet. Because of that, a WeakSet cannot be looped over and has no size. It only has add, has and delete.

Its main use is marking objects without keeping them alive, such as "this DOM element has already been set up". Most of the time a normal Set is what you want.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is new Set(["a", "b", "a", "c", "b"]).size?

    Duplicates are dropped, so the set holds "a", "b" and "c". Sets use size, not length.
  2. 2. A set already contains { id: 1 }. What does set.has({ id: 1 }) return?

    Sets compare objects by reference. The object literal in has() is a brand-new object, so it is not the one in the set.
  3. 3. You have sets wanted and owned. Which expression gives the items you still need to buy?

    wanted.difference(owned) keeps what is in wanted but not in owned. The other order would list things you own but don't want.
  4. 4. Why can set.has(x) be much faster than array.includes(x) for large collections?

    A set looks values up by hash, taking about the same time at any size. includes checks items one by one.
  5. 5. Which call throws a TypeError?

    The new Set methods need a set-like argument with size, has and keys. An array doesn't qualify; wrap it with new Set(...).

Summary

  • A Set stores each value once and remembers insertion order. Use add, has, delete, clear and the size property.
  • Values are compared with SameValueZero: like ===, except NaN equals NaN. Objects are compared by reference.
  • Convert with new Set(array) and [...set]; [...new Set(array)] removes duplicates.
  • has() is fast at any size, so build a set when you check membership inside a loop.
  • union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf and isDisjointFrom are built in since ES2025; spread and filter give the same results in older environments.
  • WeakSet holds objects weakly and can't be iterated; it is a niche tool.

Next: Maps โ€” key-value collections where the keys can be anything.