Context & History of JavaScript Set Enhancements
JavaScript introduced the Set object in ES6 to provide a collection of unique values. Early versions only offered basic add, delete and has operations. Recent engine updates, starting with Firefox 127, have added set algebra methods such as union, intersection, symmetricDifference and difference. These additions bring native support for common mathematical operations that previously required custom code or third‑party libraries.
Implementation & Best Practices
Before applying the new methods, verify browser compatibility using a feature test. Create separate Set instances for each data source, then call the desired algebra method to produce a result set. After obtaining the result, iterate with forEach to render or process the items. Keep sets small when possible to reduce memory pressure, and avoid mixing primitive and object values unless you understand reference equality.
union method
The union method returns a set containing every element that appears in either of the source sets. Example:
const setA = new Set(["apple","banana"])
const setB = new Set(["banana","cherry"])
const all = setA.union(setB)
all.forEach(item=>console.log(item))
This yields apple, banana and cherry without duplicates.
intersection method
The intersection method produces a set of values present in both source sets.
const setA = new Set(["apple","banana","pear"])
const setB = new Set(["banana","pear","peach"])
const common = setA.intersection(setB)
common.forEach(item=>console.log(item))
Only banana and pear are logged.
symmetricDifference method
This method returns elements that exist in one set or the other but not in both.
const setA = new Set(["a","b","c"])
const setB = new Set(["b","c","d"])
const diff = setA.symmetricDifference(setB)
diff.forEach(item=>console.log(item))
The output is a and d.
difference method
The difference method yields a set of items that are in the first set and not in the second.
const setA = new Set([1,2,3,4])
const setB = new Set([3,4,5])
const left = setA.difference(setB)
left.forEach(item=>console.log(item))
Result is 1 and 2.
For a deeper dive on the abstract data type behind sets, see the Wikipedia entry. When working with browser‑specific quirks, the browser heading styles guide offers useful context.