Set union

2 snippets across 2 stacks - JavaScript, Python

Also written as Set union

JSJavaScript

Set Methods (ES2025)

JS · Modern Features
Syntax
setA.union(setB)
setA.intersection(setB)
setA.difference(setB)
setA.symmetricDifference(setB)
setA.isSubsetOf(setB)
setA.isSupersetOf(setB)
setA.isDisjointFrom(setB)
Example
const frontend = new Set(["js", "css", "html", "ts"]);
const backend = new Set(["js", "python", "go", "ts"]);

console.log(frontend.union(backend));
// Set {"js", "css", "html", "ts", "python", "go"}

console.log(frontend.intersection(backend));
// Set {"js", "ts"}

console.log(frontend.difference(backend));
// Set {"css", "html"}

console.log(frontend.isSubsetOf(backend)); // false

Note ES2025. All methods return new Sets (non-mutating). Works with any iterable argument, not just Sets. Replaces manual loop-based set operations.

PYPython

Set Operations

PY · Tuples & Sets
Syntax
a | b  (union)
a & b  (intersection)
a - b  (difference)
a ^ b  (symmetric difference)
Example
frontend = {"alice", "bob", "carol"}
backend = {"bob", "carol", "dave"}

print(frontend | backend)
print(frontend & backend)
print(frontend - backend)
print(frontend ^ backend)
Output
{'alice', 'bob', 'carol', 'dave'}
{'bob', 'carol'}
{'alice'}
{'alice', 'dave'}

Note Set operations are extremely fast (O(min(len(a), len(b))) for intersection). Use them instead of nested loops for membership checks.

Frequently asked questions

How does JavaScript handle set union?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Set Methods (ES2025)" snippet in JavaScript uses `setA.union(setB)`.
Which code does the JavaScript example use?
The "Set Methods (ES2025)" snippet uses `setA.union(setB)`, from the Modern Features section of the JavaScript cheat sheet.
Which stacks cover "set union" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Set Methods (ES2025)": ES2025. All methods return new Sets (non-mutating). Works with any iterable argument, not just Sets. Replaces manual loop-based set operations.