Set Composition

Beyond simply storing unique values, modern JavaScript includes built-in methods for performing complex Set Composition logic (often called “Set Theory”).

These methods are incredibly useful when you need to compare two distinct datasets.

Intersection

The .intersection() method returns a brand new Set containing only the elements that exist in both sets.

const groupA = new Set(["Alice", "Bob", "Charlie", "David"]);
const groupB = new Set(["Alice", "David", "Eve", "Frank"]);

const shared = groupA.intersection(groupB);

console.log(shared);
// Output: Set { 'Alice', 'David' }

Difference

The .difference() method returns a new Set containing the elements that exist in the first set, but not in the second set.

const groupA = new Set(["Alice", "Bob", "Charlie", "David"]);
const groupB = new Set(["Alice", "David", "Eve", "Frank"]);

// Elements in A that are NOT in B
const exclusiveToA = groupA.difference(groupB);

console.log(exclusiveToA);
// Output: Set { 'Bob', 'Charlie' }

Union

The .union() method combines two sets together, returning a new Set containing all elements from either set (with duplicates automatically removed).

const groupA = new Set(["Alice", "Bob"]);
const groupB = new Set(["Alice", "Charlie"]);

const everyone = groupA.union(groupB);

console.log(everyone);
// Output: Set { 'Alice', 'Bob', 'Charlie' }