Photo by PJH on Unsplash

On this page

This chapter follows Arrays in JavaScript.

A Set holds unique values (primitives or object references). Duplicate inserts are ignored; NaN is treated as equal to NaN.

const numbers = [2, 3, 4, 4, 2, 3, 5];
Array.from(new Set(numbers)); // [2, 3, 4, 5]

Core API

Method / property Behavior
add(value) Insert; returns the set
delete(value) Remove; boolean success
has(value) Membership
clear() Remove all
size Count
const s = new Set([1, 2, 3]);
s.add(2).add(4);
s.has(2); // true
s.delete(1);
s.size; // 3

Construction and strings

Any iterable works: arrays, strings, other sets.

new Set("Firefox"); // Set(7) { "F", "i", "r", "e", "f", "o", "x" }
new Set("firefox"); // Set(6) { "f", "i", "r", "e", "o", "x" } — case sensitive

Convert back with Array.from(mySet) or spread into a new array when you need an Array instance.

Objects as values

Each object literal is a new reference. delete({ a: 1 }) does not remove an earlier { a: 1 } unless you kept that reference.

const mySet = new Set();
const obj = { a: "1" };
mySet.add(obj);
mySet.add({ a: "1" }); // second, distinct object
mySet.size; // 2
mySet.delete(obj); // removes the first

Iteration

keys(), values(), and entries() all yield values (sets have no separate keys). for..of uses values.

const set1 = new Set(["a", "b", "c"]);
for (const v of set1) console.log(v);
set1.entries().next(); // { value: ["a", "a"], done: false }

Set algebra (ES2025)

Native methods return new sets and do not mutate operands.

Method Meaning
a.union(b) All elements in either set
a.intersection(b) Elements in both
a.difference(b) In a but not b
a.symmetricDifference(b) In one set but not both
a.isSubsetOf(b) Every element of a is in b
a.isSupersetOf(b) b is subset of a
a.isDisjointFrom(b) No shared elements
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([2, 3]);
const setC = new Set([3, 4, 5, 6]);
setA.isSupersetOf(setB); // true
setA.union(setC); // Set {1, 2, 3, 4, 5, 6}
setA.intersection(setC); // Set {3, 4}
setA.symmetricDifference(setC); // Set {1, 2, 5, 6}
setA.difference(setC); // Set {1, 2}

Continue with Map and WeakMap.

Search articles

Type a word to search published articles.

Open the search page