Sub topic 12
Runtime support, feature detection, and fallbacks
This chapter assumes you know the four copying methods from earlier chapters and how sort, splice, and reverse mutate an array. Here you will check whether a runtime has the ES2023 methods and write fallbacks that give the same results when it does not.
Where the methods are available
toSorted, toSpliced, with, and toReversed shipped together, so a runtime that has one of them almost always has all four. These are the first versions that include them:
| Runtime | First version with the methods |
|---|---|
| Chrome / Edge | 110 |
| Firefox | 115 |
| Safari (macOS and iOS) | 16.0 |
| Node.js | 20.0 |
Older runtimes are still common in some places: Node 18 services, older embedded WebViews, and locked-down corporate browsers. Calling arr.toSorted() in one of them throws TypeError: arr.toSorted is not a function.
Feature detection
To test for a method, check that it exists on the prototype. Don't parse version strings.
Fallback helpers
Each fallback copies the array first and then runs the mutating method on the copy. Spread reads holes as undefined, so the copies come out dense, just like the native results.
const hasCopyMethods = typeof Array.prototype.toSorted === "function";
function sortedCopy(arr, compare) {
return hasCopyMethods ? arr.toSorted(compare) : [...arr].sort(compare);
}
function reversedCopy(arr) {
return hasCopyMethods ? arr.toReversed() : [...arr].reverse();
}
function splicedCopy(arr, ...args) {
if (hasCopyMethods) return arr.toSpliced(...args);
const copy = [...arr];
copy.splice(...args);
return copy;
}
function withCopy(arr, index, value) {
if (hasCopyMethods) return arr.with(index, value);
const i = Math.trunc(index) || 0;
const actual = i < 0 ? arr.length + i : i;
if (actual < 0 || actual >= arr.length) {
throw new RangeError(`Invalid index: ${index}`);
}
const copy = [...arr];
copy[actual] = value;
return copy;
}
const nums = [3, 1, 2];
console.log(sortedCopy(nums, (a, b) => a - b)); // [1, 2, 3]
console.log(reversedCopy(nums)); // [2, 1, 3]
console.log(splicedCopy(nums, 1, 1, 9)); // [3, 9, 2]
console.log(splicedCopy(nums, 1)); // [3]
console.log(withCopy(nums, -1, 0)); // [3, 1, 0]
console.log(nums); // [3, 1, 2]Two details matter for matching native behavior:
splicedCopyforwards its arguments with rest and spread instead of declaringstartanddeleteCount.splice(1)deletes to the end, butsplice(1, undefined)deletes nothing. Passing an explicitundefinedwould change the result.withCopyhas to do the index handling itself. Plain assignment tocopy[10]would grow the array, whilewiththrows aRangeError.
Polyfill or helper?
| Approach | Good for | Cost |
|---|---|---|
| Local helpers (above) | Libraries and small apps | Callers use helper names, not the native methods |
| `core-js` polyfill | Apps that want to write `arr.toSorted()` everywhere | Adds bundle size and patches global prototypes |
| Raise the minimum runtime | Server code on Node 20+ | Drops older environments |
Exercise
A teammate writes the fallback function withCopy(arr, i, v) { const c = [...arr]; c[i] = v; return c; }. Give two calls where it behaves differently from the native with.
Show answer
withCopy([1, 2, 3], -1, 0) adds a property named "-1" and returns an array that still looks like [1, 2, 3], while with returns [1, 2, 0]. withCopy([1, 2, 3], 5, 0) grows the array to length 6 with holes, while with throws a RangeError.
Exercise
Why does typeof Array.prototype.toSorted === "function" make a better check than reading the Node.js version?
Show answer
It tests the capability you actually need. It works in every runtime, including browsers, Deno, and polyfilled environments, and it stays correct even if a runtime adds the method in an unexpected version.