PREP WITH PROOF
Menu
JAVASCRIPT & SOFTWARE ENGINEERING / PRACTICAL GUIDE

JavaScript sort vs toSorted: Numeric Order, Mutation and Ties

Fix JavaScript sorting bugs with tested examples for numeric comparators, mutation, shallow copies, stable ties, sparse arrays, undefined and locale-aware ordering.

THE QUICK ANSWER

sort rearranges the original array and returns that reference; toSorted returns a new ordered array. Both need an explicit numeric comparator for ordinary finite-number arrays. The new array still shares object elements. Validate inputs and define ties separately from the mutation decision.

Separate the ordering bug from the mutation bug

A results table displays 12 before 2, and returning to another view reveals that its original array has changed order too. These are two separate decisions hidden in one call. The comparator determines ordering; choosing sort or toSorted determines whether the operation rearranges the original array or returns another array.

This guide builds a small set of explicit contracts: finite numbers for numeric sorting, score and ASCII ID for deterministic record ordering, and separate tests for array identity and nested object identity. It also examines sparse input because a visually similar result can differ in which indices actually exist.

The original examples were executed with Node.js v24.22.1. Save the seven code blocks together in their displayed order as sorting-demo.mjs and run node sorting-demo.mjs. The first block imports Node’s built-in strict assertion module. When running a later block separately, retain that import. Successful assertions are silent. These fixtures establish their stated behavior; they are not cross-browser performance measurements.

Supply a numeric comparator for ordinary number arrays

Without a comparator, ordinary Array sorting compares the string representations of defined values using UTF-16 code-unit ordering. That is why the first assertion below deliberately expects 12 before 2. For a finite-number list, returning a minus b selects ascending numeric order; b minus a selects descending order.

The original values in this fixture are all numbers, so the comparison does not need parsing. If values arrived as strings from a form or API, decide how to validate and convert them before sorting. A comparator that happens to coerce one input successfully is not a complete input policy.

The important output is the order and preserved membership, not a promise about the sorting algorithm or its runtime. An empty array, repeated values and already ordered input should remain valid under the same contract. Add those cases to your regression tests rather than testing only a hand-picked unsorted list.

import assert from 'node:assert/strict';

const values = [40, 3, 12, 2];
assert.deepEqual(values.toSorted(), [12, 2, 3, 40]);
assert.deepEqual(values.toSorted((a, b) => a - b), [2, 3, 12, 40]);
assert.deepEqual(values.toSorted((a, b) => b - a), [40, 12, 3, 2]);
assert.deepEqual(values, [40, 3, 12, 2]);

Source: MDN: Array sort and comparator behavior ↗

A new array still contains the original object references

Array.prototype.sort rearranges its receiver and returns that same array reference. toSorted produces a new array. This difference matters when a caller owns an input list that other parts of the program also use. Assigning the result of sort to a different variable does not create an independent list.

The record fixture tests a second boundary: copying the outer array does not clone the records. The result contains the same objects in another order. Editing the selected record’s score through the result also edits the original record. Use deliberate object copying or a suitable data-cloning contract when independent editable records are required.

For a dense ordinary array in a runtime without toSorted, copying the array first and sorting that copy is a useful approach. The spread example retains object references as well. Check your actual deployment target for method availability; do not turn a missing method into an implicit change in mutation behavior.

const mutable = [8, 1, 4];
const sameArray = mutable.sort((a, b) => a - b);
assert.equal(sameArray, mutable);
assert.deepEqual(mutable, [1, 4, 8]);

const records = [{ id: 'B', score: 8 }, { id: 'A', score: 1 }];
const ordered = records.toSorted((a, b) => a.score - b.score);
assert.notEqual(ordered, records);
assert.equal(ordered[0], records[1]);
ordered[0].score = 7;
assert.equal(records[1].score, 7);
const copiedOrder = [...records].sort((a, b) => a.score - b.score);
assert.notEqual(copiedOrder, records);
assert.equal(copiedOrder[0], records[1]);

Source: MDN: toSorted and sparse arrays ↗

Return a signed comparison, not a Boolean

A comparator’s negative, zero and positive results express before, equal and after. Returning a greater-than Boolean fails to express the negative direction: swapping the pair produces zero instead of the opposite sign. Do not rely on a particular observed output from that malformed comparator, because it does not define the intended ordering consistently.

Keep comparison results consistent across repeated calls, avoid changing the records during comparison, and preserve transitivity. If a precedes b and b precedes c, the policy must not also put c before a. A comparator that reads changing external state can undermine these properties even when its arithmetic looks correct.

NaN is another boundary. A comparator result of NaN is treated as equality by the array comparison operation. Subtracting invalid values can therefore hide missing-data problems as ties. Decide whether invalid values should be rejected or assigned an explicit ordering before asking the sort to arrange them.

const broken = (a, b) => a > b;
assert.equal(Number(broken(2, 1)), 1);
assert.equal(Number(broken(1, 2)), 0); // Not the opposite sign.
const ascending = (a, b) => a - b;
assert.equal(Math.sign(ascending(2, 1)), 1);
assert.equal(Math.sign(ascending(1, 2)), -1);
assert.equal(ascending(2, 2), 0);

Source: ECMAScript: CompareArrayElements and comparator consistency ↗

Choose a finite, dense numeric-input policy explicitly

The helper below accepts only a dense ordinary array whose every element is a finite Number. It rejects numeric strings, NaN, infinities, undefined and missing indices. This is a teaching contract for a numeric list, not a universal definition of which JavaScript values may be sorted.

Number.isFinite does not first convert a string into a number. Checking each index also avoids a subtle validation gap: iteration helpers that skip holes can report success without having validated every logical position in a sparse array. The explicit own-property check makes the dense-input requirement visible.

Rejecting Infinity here is a policy choice. Some applications need infinite bounds, missing values or BigInt identifiers; they should define and test another comparator and validation boundary. Avoid routing a mixed domain through subtraction just because it produces a Number for several of your examples.

function sortedFiniteNumbers(input) {
  if (!Array.isArray(input)) throw new TypeError('Expected an array');
  for (let i = 0; i < input.length; i += 1) {
    if (!Object.hasOwn(input, i) || !Number.isFinite(input[i])) {
      throw new TypeError('Expected dense finite numbers');
    }
  }
  return input.toSorted((a, b) => a - b);
}
assert.deepEqual(sortedFiniteNumbers([2, -1, 2, 0]), [-1, 0, 2, 2]);
assert.deepEqual(sortedFiniteNumbers([]), []);
for (const invalid of [[NaN], [Infinity], ['2'], [undefined], new Array(1), null]) {
  assert.throws(() => sortedFiniteNumbers(invalid), TypeError);
}

Source: MDN: Number.isFinite validation ↗

Stable ties preserve incoming order; an explicit key defines another policy

A stable sort preserves the relative input order of elements that compare equal. That is useful when incoming order is meaningful. It does not make a result independent of the incoming list: if a service returns equal-score records in a different order, a score-only stable sort can preserve that different order.

The next fixture defines ascending score followed by ascending ASCII ID. Its records have finite scores and unique ASCII IDs, so the tie rule produces the same ID sequence when this input is reversed. If IDs are duplicated, equal score-and-ID records still require a further rule when their relative order must be independent of input.

The tie breaker is an application policy, not a claim that ASCII order is appropriate for displayed personal names. Keep machine identity ordering separate from human-language collation. For multi-field ranking, document which fields dominate, which direction each field uses and what happens when all compared fields are equal.

const entries = [{ id: 'B', score: 2 }, { id: 'C', score: 1 }, { id: 'A', score: 2 }];
const scoreOnly = entries.toSorted((a, b) => a.score - b.score);
assert.deepEqual(scoreOnly.map(x => x.id), ['C', 'B', 'A']);
const asciiId = (a, b) => a < b ? -1 : a > b ? 1 : 0;
const scoreThenId = (a, b) => a.score - b.score || asciiId(a.id, b.id);
assert.deepEqual(entries.toSorted(scoreThenId).map(x => x.id), ['C', 'A', 'B']);
assert.deepEqual([...entries].reverse().toSorted(scoreThenId).map(x => x.id), ['C', 'A', 'B']);

Source: ECMAScript: stable SortIndexedProperties ↗

Inspect index presence when sparse arrays are intentional

An empty array slot and an element whose value is undefined can look similar when read through indexing, but they are not the same property state. sort retains holes and moves them to the end, after undefined values. toSorted reads holes as undefined and produces corresponding present elements in its new result.

The fixture uses Object.hasOwn to test that distinction. Both displayed orders start with 1 and 3, yet the final position is absent in the mutated sparse array and present in the toSorted result. Comparing only JSON output would lose this distinction, so index-presence assertions are more useful here.

Undefined elements are placed at the end without being passed to the comparator. A callback intended to put bare undefined elements first therefore does not get to enforce that rule directly. Normalize the data into explicit records or another representation when a custom missing-value policy is needed.

const sparse = [3, , 1, undefined];
const denseCopy = sparse.toSorted((a, b) => a - b);
assert.deepEqual(denseCopy, [1, 3, undefined, undefined]);
assert.equal(Object.hasOwn(denseCopy, 3), true);
assert.equal(Object.hasOwn(sparse, 1), false);
sparse.sort((a, b) => a - b);
assert.equal(sparse[0], 1);
assert.equal(sparse[1], 3);
assert.equal(Object.hasOwn(sparse, 2), true);
assert.equal(Object.hasOwn(sparse, 3), false);

Source: MDN: toSorted and sparse arrays ↗

Text collation and typed arrays have different defaults

For human-facing text, choose a locale and comparison options deliberately. Intl.Collator supports language-aware comparison and options such as numeric ordering within strings. The filename example checks that file2 precedes file10 under an explicit English numeric collation; it does not assert a universal ordering for every locale or every Unicode string.

Typed arrays are another reason to identify the receiver before diagnosing a result. Their default sort is numeric, unlike the default string ordering of ordinary arrays. The Uint8Array example demonstrates that distinction without a comparator. Do not infer ordinary Array behavior from a typed-array test or vice versa.

The selected examples were executed in the stated Node runtime. Locale data and available methods are properties of the actual runtime you deploy. Check those requirements with representative data rather than inferring compatibility from the fact that another development machine has the same language syntax.

const filenames = ['file10', 'file2'];
const collator = new Intl.Collator('en', { numeric: true });
assert.deepEqual(filenames.toSorted(collator.compare), ['file2', 'file10']);
const typed = new Uint8Array([40, 3, 12, 2]);
assert.equal(typed.sort(), typed);
assert.deepEqual(Array.from(typed), [2, 3, 12, 40]);

Source: MDN: Intl.Collator ↗

Test the ordering contract rather than one screenshot

For a production sorting bug, capture the receiver type, original values, comparator and mutation requirement. Then test output order, preserved membership, reference identity and the declared tie behavior separately. Include empty input, duplicates, equal keys, reversed input and values your validator should reject.

When testing a comparator itself, check its sign in both directions and compare each value with itself. For a bounded fixture set, also check triples for transitivity. Keep those checks separate from output assertions: a broken comparator can accidentally produce the expected order for one list. For record sorting, verify that the comparator does not change scores or IDs while it runs. If the source is frozen or shared with a UI store, test the mutation boundary directly rather than relying on a name such as sortedResults to imply a copy. Review missing-value handling before treating two records as equal.

The accompanying regression checks also compare 300 seeded finite-number and record cases with an independent Python ordering oracle. They cover the stated numeric and ASCII policies; they do not establish a performance ranking between sort and toSorted or certify an arbitrary comparator. Keep the comparator’s domain narrow enough that the assertions explain what correctness means.

Choose sort when changing the owned array is intentional. Choose toSorted when you need another ordered array, while remembering that its objects can still be shared. Supply a valid comparator, validate the input domain and state the tie policy. Those choices resolve different failure modes and should remain visible in code review.

RequirementChoiceVerify
Rearrange an owned arraysort with a valid comparatorSame array reference; desired order
Keep the original array ordertoSortedNew array; original unchanged
Independent editable objectsSeparate cloning decisionNested identity and mutations
Finite numeric ascendingValidated values; a minus bReject unsupported inputs
Input-independent record orderExplicit additional tie keyPermuted input gives the declared sequence
KEEP THESE THREE THINGS

Your next steps

  1. Choose mutation and ordering policies separately.
  2. Validate comparator inputs and test ties explicitly.
  3. Check object identity and sparse-index presence when they matter.

Sources & official resources

Linked resources checked on 2026-11-06. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →