Sub topic 11
Browser Support, Feature Detection, and Fallbacks
This chapter assumes you already know the seven Set composition methods covered earlier, the set-like protocol (size, has, keys), and how spread and Array.prototype.filter work. Here the question is practical: where can you call union and its siblings safely, how can your code tell whether they exist, and what should it do when they don't?
Where the Methods Exist
The methods were standardized in ES2025. All major engines shipped them by mid-2024, so the platform as a whole has supported them only since then. Any runtime older than the versions below has none of the seven methods.
| Runtime | First version with Set methods | Released |
|---|---|---|
| Safari (macOS and iOS) | 17 | September 2023 |
| Chrome and Edge | 122 | February 2024 |
| Firefox | 127 | June 2024 |
| Node.js | 22 | April 2024 |
| Deno | 1.42 | March 2024 |
Every engine shipped all seven methods in the same release: union, intersection, difference, symmetricDifference, isSubsetOf, isSupersetOf, and isDisjointFrom. You will not find a mainstream engine that has union but lacks isDisjointFrom.
The gaps you are likely to hit in practice are:
- Node.js 18 and 20 LTS lines, which are still common on servers and in CI images.
- Users on older iOS versions, because Safari updates only with the operating system.
- Corporate or kiosk environments pinned to old browser builds.
- Embedded JavaScript engines (some serverless edge runtimes, older Electron apps, React Native's older Hermes builds) that lag behind browsers.
Choosing a Strategy
You have three reasonable options, and the right one depends on who runs your code.
- Call the methods directly. This works when you control the runtime, for example a server pinned to Node.js 22 or later, or an internal tool used only on current browsers.
- Use a polyfill. A polyfill installs missing methods on
Set.prototype, so the rest of your code callsa.union(b)as if it were native. Thecore-jslibrary provides one. If your build already usescore-jsthrough Babel'spreset-env, it can inject the polyfill automatically based on your browser targets. - Use local helper functions. Helpers are standalone functions such as
union(a, b)that call the native method when it exists and run equivalent logic when it doesn't. This approach is sometimes called a "ponyfill". It never modifies global objects, which makes it the safe choice for libraries that other people install.
Feature Detection
Feature detection means checking whether a method exists before calling it. Checking the runtime's version or user-agent string is the wrong approach: version strings are unreliable, and they tell you nothing about polyfills that are already loaded.
The basic check looks at Set.prototype:
const hasNativeUnion = typeof Set.prototype.union === "function";
console.log(hasNativeUnion); // true on Node.js 22+, false on Node.js 20Since engines shipped all seven methods together, one check is usually enough. Checking all seven costs almost nothing, though, and it protects you from partial polyfills:
const SET_METHODS = [
"union",
"intersection",
"difference",
"symmetricDifference",
"isSubsetOf",
"isSupersetOf",
"isDisjointFrom",
];
const hasSetMethods = SET_METHODS.every(
(name) => typeof Set.prototype[name] === "function"
);
console.log(hasSetMethods);Run the check once at module load, not inside a hot loop. The answer will not change while the program runs, unless a polyfill loads later. In that case, load the polyfill before any code that runs the check.
The Simple Fallbacks
The most compact fallbacks use spread and filter:
function union(a, b) {
return typeof a.union === "function" ? a.union(b) : new Set([...a, ...b]);
}
function intersection(a, b) {
return typeof a.intersection === "function"
? a.intersection(b)
: new Set([...a].filter((x) => b.has(x)));
}
function difference(a, b) {
return typeof a.difference === "function"
? a.difference(b)
: new Set([...a].filter((x) => !b.has(x)));
}
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log([...union(a, b)]); // [1, 2, 3, 4]
console.log([...intersection(a, b)]); // [2, 3]
console.log([...difference(a, b)]); // [1]These functions give the same results as native methods when both arguments are real Sets of primitives. They also share two properties with the native methods: they return a new Set and leave both inputs alone, and new Set(...) deduplicates with SameValueZero, the same comparison native Sets use.
The behavior differs in some edge cases, and each difference can cause a bug that shows up on only one runtime.
Where Simple Fallbacks Diverge from Native
Arrays are accepted instead of rejected
Native methods require a set-like argument and throw a TypeError for an array. The spread version of union accepts any iterable:
function naiveUnion(a, b) {
return new Set([...a, ...b]);
}
console.log([...naiveUnion(new Set([1]), [2, 3])]); // [1, 2, 3]On an old runtime, union(tags, ["x"]) works. On a new runtime, the same call throws. Code that passes local tests on Node.js 20 can then crash in production on Node.js 22. The safest fix is to make the fallback validate its argument the same way the native method does.
Maps and custom set-likes behave differently
[...b] iterates a Map as [key, value] pairs, but the native union uses b.keys() and adds only the keys. The naive fallback puts arrays into your result:
const counts = new Map([["c", 2]]);
console.log([...new Set([...new Set(["a"]), ...counts])]); // ["a", ["c", 2]]The native new Set(["a"]).union(counts) gives ["a", "c"].
Intersection order can differ
The specification lets intersection iterate whichever set is smaller. When the receiver is larger than the argument, the native method walks the argument's keys, so the result follows the argument's order. The filter fallback always follows the receiver's order. Both results contain the same elements, so the difference matters only when your code depends on order, such as UI lists or snapshot tests.
A Fallback That Matches Native Behavior
The module below reproduces the native argument check and uses has and keys() the same way the specification does. It reads keys() through the iterator's next method, so it also accepts custom set-like objects whose iterators are not themselves iterable.
function toSetRecord(other) {
if (other === null || (typeof other !== "object" && typeof other !== "function")) {
throw new TypeError("Argument must be a set-like object");
}
const size = Number(other.size);
if (Number.isNaN(size)) {
throw new TypeError("Set-like size must be a number");
}
if (size < 0) {
throw new RangeError("Set-like size must not be negative");
}
if (typeof other.has !== "function" || typeof other.keys !== "function") {
throw new TypeError("Set-like must have has and keys methods");
}
return other;
}
function forEachKey(other, callback) {
const iterator = other.keys();
let step = iterator.next();
while (!step.done) {
if (callback(step.value) === false) return;
step = iterator.next();
}
}
const native = (name) => typeof Set.prototype[name] === "function";
export function union(a, b) {
if (native("union")) return a.union(b);
toSetRecord(b);
const result = new Set(a);
forEachKey(b, (key) => { result.add(key); });
return result;
}
export function intersection(a, b) {
if (native("intersection")) return a.intersection(b);
toSetRecord(b);
return new Set([...a].filter((x) => b.has(x)));
}
export function difference(a, b) {
if (native("difference")) return a.difference(b);
toSetRecord(b);
return new Set([...a].filter((x) => !b.has(x)));
}
export function symmetricDifference(a, b) {
if (native("symmetricDifference")) return a.symmetricDifference(b);
toSetRecord(b);
const result = new Set(a);
forEachKey(b, (key) => {
if (a.has(key)) result.delete(key);
else result.add(key);
});
return result;
}
export function isSubsetOf(a, b) {
if (native("isSubsetOf")) return a.isSubsetOf(b);
toSetRecord(b);
if (a.size > b.size) return false;
return [...a].every((x) => b.has(x));
}
export function isSupersetOf(a, b) {
if (native("isSupersetOf")) return a.isSupersetOf(b);
toSetRecord(b);
if (a.size < b.size) return false;
let ok = true;
forEachKey(b, (key) => {
if (!a.has(key)) { ok = false; return false; }
});
return ok;
}
export function isDisjointFrom(a, b) {
if (native("isDisjointFrom")) return a.isDisjointFrom(b);
toSetRecord(b);
return [...a].every((x) => !b.has(x));
}Save it as set-helpers.mjs and try it from another module:
import { union, intersection, isSubsetOf } from "./set-helpers.mjs";
const tags = new Set(["a", "b"]);
const counts = new Map([["b", 1], ["c", 2]]);
console.log([...union(tags, counts)]); // ["a", "b", "c"]
console.log([...intersection(tags, counts)]); // ["b"]
console.log(isSubsetOf(new Set(["a"]), tags)); // true
try {
union(tags, ["c"]);
} catch (err) {
console.log(err instanceof TypeError); // true on every runtime
}Because the fallback rejects arrays just as the native method does, a mistake surfaces on every runtime rather than only on new ones. The fallback keeps one known difference: intersection always follows the receiver's order, while the native method may follow the argument's order when the receiver is larger. If order matters to you, sort the result or build it explicitly from the set whose order you want.
Performance Notes
The native methods run inside the engine and avoid creating intermediate arrays. The spread-and-filter fallbacks allocate an array the size of the receiver, then a new Set. For sets with a few thousand elements the cost is negligible. For very large sets in tight loops on old runtimes, a manual for...of loop that adds to a result Set avoids the extra array:
function differenceLoop(a, b) {
const result = new Set();
for (const x of a) {
if (!b.has(x)) result.add(x);
}
return result;
}
console.log([...differenceLoop(new Set([1, 2, 3]), new Set([2]))]); // [1, 3]Both versions do O(n) has lookups. The loop version only saves memory.
Exercises
Exercise
Your library's tests pass on Node.js 20, but a user on Node.js 22 reports "TypeError" from union(selected, ["extra"]). Your helper is typeof a.union === "function" ? a.union(b) : new Set([...a, ...b]). Explain the cause and give two fixes.
Show answer
On Node.js 20 the fallback runs, and spread accepts any iterable, including arrays. On Node.js 22 the native union runs, and it requires a set-like argument with a numeric size, which an array lacks, so it throws. Fix the caller by wrapping the array with new Set(["extra"]). Also make the fallback validate its argument (check size, has, and keys) so the mistake fails on every runtime and shows up in tests.
Exercise
Why is checking typeof Set.prototype.isDisjointFrom === "function" better than checking that process.version is at least v22?
Show answer
Feature detection tests the capability you actually need. It also works in browsers, which have no process.version, and it returns true when a polyfill has already installed the method. Version checks break on other runtimes, on forks, and on environments that report misleading versions.
Exercise
With native methods, new Set([1, 2, 3, 4]).intersection(new Set([4, 3])) may produce [4, 3], while the filter fallback produces [3, 4]. Which statement about the two results is always true, and how would you make the order deterministic?
Show answer
Both results always contain exactly the same elements; only their iteration order can differ, because the native method may iterate the smaller argument. To get a fixed order, filter the set whose order you want yourself, as in new Set([...a].filter((x) => b.has(x))), or sort the result before displaying it.