Sub topic 12
Runtime support, feature detection, and fallbacks
This chapter assumes you know sort, splice, and the spread operator, and that you have already worked through toSorted, toSpliced, and with earlier in this tutorial. Here we look at where these methods exist, how to check for them at runtime, and how to write fallbacks that behave the same way when they are missing.
Where the methods are available
The Change Array by Copy proposal reached stage 4 in early 2023 and became part of ES2023. Engines shipped it around that time. The table below lists the first version of each major runtime that supports toSorted, toSpliced, with, and toReversed on Array.prototype.
| Runtime | First version with support | Released |
|---|---|---|
| Chrome and Edge | 110 | February 2023 |
| Safari (macOS and iOS) | 16.0 | September 2022 |
| Firefox | 115 | July 2023 |
| Node.js | 20.0.0 | April 2023 |
| Deno | 1.31 | February 2023 |
| Bun | 1.0 | September 2023 |
The gaps are what matter in practice. Node.js 18 does not have these methods, and plenty of CI images, serverless runtimes, and Docker base images still run it. Firefox ESR 102 lacks them too, as do older embedded webviews and many smart TV browsers. If your code runs anywhere you don't control, assume some users will hit a runtime without toSorted.
Why a transpiler alone does not help
Babel or TypeScript can rewrite new syntax, such as optional chaining, into older syntax. toSorted is not syntax. It is a property lookup followed by a call, so arr.toSorted(cmp) is valid ES5 syntax. A transpiler leaves it as it is, and an old runtime throws:
// On Node.js 18:
const scores = [3, 1, 2];
scores.toSorted(); // TypeError: scores.toSorted is not a functionYou have two ways to close the gap. A polyfill installs the missing methods on the prototype before your code runs. A fallback checks for the method where it is used and does the equivalent work some other way. You can also combine them.
TypeScript adds a separate problem at compile time. The type definitions for these methods live in lib.es2023.array.d.ts, which TypeScript 5.2 added. If your tsconfig.json sets "lib" or "target" below ES2023, the compiler reports Property 'toSorted' does not exist on type 'number[]'. Raising lib fixes the type error, but it doesn't make the method exist at runtime. The type checker trusts that you have arranged a polyfill or a modern runtime.
Feature detection
To detect the method, check that it exists on the prototype and is a function:
const hasChangeArrayByCopy =
typeof Array.prototype.toSorted === "function" &&
typeof Array.prototype.toSpliced === "function" &&
typeof Array.prototype.with === "function";
console.log(hasChangeArrayByCopy); // true on Node.js 20+, false on Node.js 18Engines shipped all four methods together, so checking one usually tells you about the others. Checking each method you use costs almost nothing and protects you against partial polyfills.
Run the check once, at module load, and store the result. Don't use "toSorted" in [] as the test, because a non-function value on the prototype would pass it. Don't test with try { [].toSorted() } catch {} either. That approach hides real errors and does unnecessary work.
The simplest fallback has the shape below. It is correct for toSorted because spreading and then sorting gives the same result:
function sortedCopy(arr, compare) {
if (typeof Array.prototype.toSorted === "function") {
return arr.toSorted(compare);
}
return [...arr].sort(compare);
}
console.log(sortedCopy([3, 1, 2], (a, b) => a - b)); // [1, 2, 3]Writing fallbacks that match the spec
A fallback that only works in the common case causes bugs that appear on one runtime and not another. These are the details to get right for each method.
toSorted: spread, not slice
[...arr] and Array.from(arr) read holes as undefined and produce a dense array, which is what toSorted does. arr.slice() keeps the holes. sort then moves holes after any undefined values while keeping them as holes, so the result has the same visible order but behaves differently:
const sparse = [3, , 1];
const viaSlice = sparse.slice().sort();
const viaSpread = [...sparse].sort();
console.log(1 in viaSpread); // true (index 2 holds undefined, all slots exist)
console.log(2 in viaSlice); // false (index 2 is still a hole)Use spread or Array.from in your fallbacks.
toSpliced: preserve how many arguments were passed
splice and toSpliced treat an omitted deleteCount differently from an explicit undefined. months.toSpliced(1) deletes everything from index 1 onward. months.toSpliced(1, undefined) deletes nothing. A fallback with fixed parameters like (arr, start, deleteCount, ...items) always passes deleteCount along, even when the caller left it out, and that changes the result. Forward the original arguments instead:
function splicedCopy(arr, ...args) {
if (typeof Array.prototype.toSpliced === "function") {
return arr.toSpliced(...args);
}
const copy = [...arr];
copy.splice(...args);
return copy;
}
const months = ["Jan", "Mar", "Apr", "May"];
console.log(splicedCopy(months, 1, 0, "Feb")); // ["Jan", "Feb", "Mar", "Apr", "May"]
console.log(splicedCopy(months, 1)); // ["Jan"]
console.log(splicedCopy(months, 1, undefined)); // ["Jan", "Mar", "Apr", "May"]
console.log(months); // ["Jan", "Mar", "Apr", "May"]Note that the fallback returns copy, not the return value of splice. splice returns the deleted elements, and returning that by mistake is the most common bug in hand-written versions.
with: relative index and RangeError
copy[index] = value is not equivalent to with. Bracket assignment with -1 creates a property named "-1", and assignment past the end grows the array. with counts negative indices from the end and throws a RangeError when the index is out of range. The fallback has to do both:
function withCopy(arr, index, value) {
if (typeof Array.prototype.with === "function") {
return arr.with(index, value);
}
const len = arr.length;
const relative = Math.trunc(Number(index)) || 0;
const actual = relative >= 0 ? relative : len + relative;
if (actual < 0 || actual >= len) {
throw new RangeError("Invalid index : " + index);
}
const copy = [...arr];
copy[actual] = value;
return copy;
}
const values = [1, 2, 3, 4, 5];
console.log(withCopy(values, -1, 0)); // [1, 2, 3, 4, 0]
try {
withCopy(values, 10, 0);
} catch (err) {
console.log(err instanceof RangeError); // true
}Math.trunc(Number(index)) || 0 follows the spec's integer conversion closely enough for real use. NaN becomes 0, 2.7 becomes 2, and Infinity stays Infinity, so it fails the range check.
Polyfills: when and how
If you build an application and control its entry point, a maintained polyfill is usually the best option. Your code calls arr.toSorted() directly, and once every target runtime supports the method you can remove the polyfill without touching call sites. With core-js you can import only what you need:
// At the very top of the app entry file
import "core-js/actual/array/to-sorted";
import "core-js/actual/array/to-spliced";
import "core-js/actual/array/with";You can instead configure @babel/preset-env with useBuiltIns: "usage" and a browserslist target. Babel then injects only the polyfills that your targets need, based on the methods your code calls.
Choosing a strategy
| Situation | Recommended approach |
|---|---|
| Node.js 20+ service, or a browser app targeting browsers from 2023 onward | Call the methods directly and set `lib` to `ES2023` |
| Browser app with older targets | core-js polyfill through the entry point or preset-env |
| Published npm library | Local helpers with feature detection, no global patching |
| Code shared between Node.js 18 and 20 | Helpers or polyfill until Node.js 18 is dropped |
Whatever you pick, run your tests on the oldest runtime you support. A test suite that only runs on Node.js 22 will never execute your fallback branch, and you won't find out that it is broken until a user does.
Exercise
A teammate writes this fallback for with: const copy = arr.slice(); copy[index] = value; return copy;. List the ways its behavior differs from the native method when called as withFallback([1, 2, 3], i, 0).
Show answer
With i = -1, it adds a property named "-1" and leaves index 2 unchanged instead of returning [1, 2, 0]. With i = 5, it grows the array to length 6 with holes instead of throwing a RangeError. With a sparse input, slice keeps the holes, while the native method fills them with undefined.
Exercise
Your TypeScript project compiles with "lib": ["ES2023"] and your tests pass locally on Node.js 22, but production on Node.js 18 throws "toSorted is not a function". Why didn't the compiler catch this, and what are two ways to fix it?
Show answer
The lib setting only tells the type checker which APIs to assume exist. It doesn't add the methods at runtime, and TypeScript doesn't transform method calls. Fix it by upgrading production to Node.js 20 or later, or by loading a polyfill such as core-js/actual/array/to-sorted at startup. You could also replace the calls with feature-detecting helpers.
Exercise
Why does splicedCopy(arr, 1) in this chapter forward ...args instead of declaring (arr, start, deleteCount, ...items) and calling copy.splice(start, deleteCount, ...items)?
Show answer
With fixed parameters, an omitted deleteCount gets passed to splice as an explicit undefined. splice treats undefined as 0 and deletes nothing, while an omitted deleteCount deletes to the end. Forwarding the original arguments keeps the same number of arguments, so the fallback behaves like the native toSpliced.