A catalogue sorts quantities and places 120 before 18 and 4. Another row appears blank, and two empty slots move to the end. The browser has not necessarily lost arithmetic control. An ordinary array's default sorting contract differs from numeric comparison, and present undefined values differ from missing indexed properties.
The short answer is that ordinary default Array.prototype.sort compares the string forms of non-undefined values. It places undefined values after other values without passing them to a supplied comparator. In a controlled sparse ordinary array, missing positions end up after the sorted present entries. A numeric comparator changes the comparison of eligible values, but it does not turn every missing-data case into a valid quantity.
This guide follows original seven-position ledgers, then changes comparison rules, property presence and result ownership. It uses ordinary arrays with standard prototypes and controlled data unless a chapter explicitly changes those conditions. The examples are explanations of language behaviour, not a benchmark or a claim about every possible JavaScript object.
This specialist guide belongs to the Websites root. It also connects to The Gold Standard of Education | Learning That Transfers into Life and the How X Works hub. The worked cases are original teaching examples; their numbers are stipulated so that the reasoning can be checked.
eduKateSG · Websites
Find your next learning step
Trace ordinary array comparison and property presence. Work default string order, numeric comparators, undefined entries, missing slots, stability and new results.
ROUTE 1 · CHAPTERS 1–3
Establish values and representations
Record the sparse input, default comparison strings and retained types.
ROUTE 2 · CHAPTERS 4–6
Work comparison and missing positions
Trace numeric order, undefined handling and the sparse tail.
ROUTE 3 · CHAPTERS 7–8
Check identity and ties
Compare new results and stable ordering of distinct records.
ROUTE 4 · CHAPTERS 9–11
Connect sorting to the reader task
Choose input, code and display policies deliberately.
ROUTE 5 · CHAPTERS 12–14
Test and transfer
Check invariants, changed quantities and complete result shapes.
Chapter contents
Establish values and representations · Chapters 1–3
1. Write the complete input shape before predicting order
2. Compare the numeric values through their string forms
3. Keep comparison conversion separate from stored value type
Work comparison and missing positions · Chapters 4–6
4. Supply a numeric comparator for a valid numeric domain
5. Place undefined values without expecting comparator calls for them
Check identity and ties · Chapters 7–8
7. Compare in-place sort with a newly sorted array
8. Use stability without turning equal keys into equal records
Connect sorting to the reader task · Chapters 9–11
9. Define an invalid-data policy before sorting
10. Choose quantity order and symbolic-code order deliberately
Test and transfer · Chapters 12–14
12. Test invariants rather than one engine's comparison itinerary
CHAPTER 1 OF 14 · Establish values and representations
1. Write the complete input shape before predicting order
Start with an ordinary array of length seven. Index zero contains 18. Index one is present and stores undefined. Index two is missing. Index three contains 4, index four contains 120, index five is present and stores undefined, and index six is missing. These positions define the central fixture.
There are three numeric values, two present undefined values and two missing positions. Those counts add to seven, but they do not describe seven stored values. Length and the number of present indexed properties are different observations. A printed comma or blank cell is not enough to tell them apart.
Assume there are no inherited indexed values and no accessors interfering with the array. That boundary matters because property lookup can behave differently when prototypes or getters supply values. The first fixture removes those conditions so the distinction between values and holes is visible.
const values = [18, undefined, , 4, 120, undefined, ,];
// length is 7; own indices are 0, 1, 3, 4 and 5.
Before calling sort, record both each value's type and whether its numeric property exists. This lets the later check distinguish a reordered numeric value, an explicit undefined value and a missing slot. A display that renders all three as empty text would conceal the input contract.
The website task also needs a requirement. Are these fields quantities, symbolic catalogue codes or missing observations? The algorithm cannot infer that meaning from their appearance. For the first trace, ask only what ordinary default sorting does to the stated array. We will separately decide whether that result serves a quantity display.
CHAPTER 2 OF 14 · Establish values and representations
2. Compare the numeric values through their string forms
The three numbers have string forms 18, 4 and 120. Default ordinary array comparison uses those forms rather than subtracting the quantities. Compare 120 with 18: their first characters both represent 1, and the next characters are 2 and 8. Under this comparison, 120 precedes 18.
Compare 18 with 4. Their first characters differ, and 1 precedes 4. The resulting order of these three values is therefore 120, 18, 4. This is a string-order result applied to the numbers' comparison forms, not an ascending numerical result.
The first-principles check examines the first differing code unit rather than the number of digits or arithmetic magnitude. A longer printed number can precede a shorter one. The numeric statement 120 is greater than 18 remains true; the sorting operation simply did not use that numeric relation by default.
Change the values to 6, 42 and 305. Their default order is 305, 42, 6 in this ordinary fixture. The same reasoning applies at the first character. This changed-number exercise prevents the learner from memorising one surprising list without understanding the comparison rule behind it.
String comparison here should not be described as a universal human dictionary order. JavaScript's default comparison operates on string representations under its specified relation. Locale-aware text ordering is another requirement with its own tools and settings, particularly when names and writing systems are involved.
For a paper ledger, write original numeric value beside comparison string, then the resulting relative position. Keeping those columns separate reveals the mistaken assumption immediately. The values are numerical quantities, but the selected ordering rule compares their representations. A correct implementation of that rule can still be unsuitable for the reader's intended task.
CHAPTER 3 OF 14 · Establish values and representations
3. Keep comparison conversion separate from stored value type
Default sorting's use of string forms does not mean every stored number becomes a string in the array. After the controlled sort, the numeric entries remain numbers. A comparison representation and a replacement data representation are different operations.
Use a second fixture containing the number 4, the string "18" and the number 120. Their default comparison forms can place 120 before the string 18 and then the number 4. Inspect types after sorting to see that the original string remains a string while the numeric entries remain numbers.
This matters when a later calculation follows the sort. A visually numeric cell may still carry text, and addition can have a different meaning from arithmetic addition if the application has not established value types. Sorting does not validate or normalise a mixed source for later computation.
A comparator can also treat distinct stored values as equivalent under a chosen key. The number 4 and the string "4" have equal default string comparison forms in the controlled example. Equal comparison keys do not make their types or identities equal.
Do not extend the primitive fixture carelessly to objects. Obtaining an object's comparison string can invoke conversion behaviour supplied by that object, and a failing conversion can interrupt the operation. If the application sorts records, an explicit stable key obtained under an understood contract is easier to reason about than an unexplained object conversion.
For the evidence check, preserve values, types and identities where relevant. A text-only screenshot cannot prove that numeric values were converted or that a mixed source was repaired. The useful report says which representation decided order and which original values were subsequently stored in the reordered array.
CHAPTER 4 OF 14 · Work comparison and missing positions
4. Supply a numeric comparator for a valid numeric domain
For ordinary finite Number values, a comparator such as (a, b) => a - b expresses ascending numeric comparison. A negative result places a before b, a positive result places it after b and zero treats the pair as equal for that ordering. The sign is the important part, not a required result of exactly minus one or one.
Apply that comparator to a fresh ordinary array containing 18, 4 and 120. The resulting numeric order is 4, 18, 120. Now 4 minus 18 is negative, while 120 minus 18 is positive. The comparison has changed from string forms to arithmetic relationships on the stated finite numeric domain.
const values = [18, 4, 120];
values.sort((a, b) => a - b);
// values is [4, 18, 120].
Avoid a Boolean comparator such as (a, b) => a > b. It supplies zero or one after ordinary conversion, leaving the less-than case indistinguishable from equality. That does not express the full consistent comparison relation the author intended. One apparently sorted test list is not enough evidence that the comparator is valid.
Test the comparator directly on a smaller value, a larger value and an equal pair. Then test ordering across a triple. These checks examine the contract independently of a particular engine's comparison sequence. A sorter is not required to ask about pairs in the same order your paper working used.
Keep the numeric domain explicit. The subtraction comparator is useful for these finite Number quantities. It is not an automatic parser, missing-data policy, BigInt comparator or locale-aware text comparator. Additional input categories require their own representation and validation decisions before the result can be called a correctly ordered quantity list.
A typed array introduces a different built-in method. For example, a Uint16Array containing 18, 4 and 120 has a numeric default sorting contract, so its own sort can produce 4, 18, 120 without the ordinary array's subtraction callback. That does not contradict the earlier default result. The receiver and selected method changed.
Do not use that observation as a shortcut for repairing arbitrary catalogue data. Constructing a typed array has its own numeric representation and conversion rules, and it does not preserve the central fixture's ordinary sparse property shape. Changing containers can change data before sorting begins. The comparison should identify those representation changes rather than crediting a different container with an unexplained universal improvement.
CHAPTER 5 OF 14 · Work comparison and missing positions
5. Place undefined values without expecting comparator calls for them
Return to the central seven-position fixture. Its two present undefined values are handled separately from the ordinary non-undefined comparisons. With the default rule, the numeric entries appear as 120, 18, 4, followed by the two present undefined values, before the missing tail positions.
With the ascending numeric comparator, the three numeric entries instead become 4, 18, 120. The undefined values still follow those non-undefined values. They are not supplied as arguments to the comparator in this ordinary array contract, so a comparator branch checking for undefined does not control their placement here.
A useful check records every comparator argument in a fresh fixture and asserts that none is undefined. Do not assert an exact number of calls or a universal order of argument pairs. The meaningful observation is the category excluded from those calls and the resulting positions in the array.
Now reverse numeric order using a suitable descending comparator. The non-undefined values become 120, 18, 4, but the undefined values still follow them. Descending numeric comparison does not, by itself, move undefined to the beginning. Their special handling is not simply another numeric value being reversed.
Distinguish the actual undefined value from the string "undefined". The string is a present non-undefined value and participates through the relevant comparison contract. Rendering both as the same visible word does not give them the same behaviour or the same data meaning.
For the catalogue, do not use undefined as a silently accepted quantity just because sort can place it. Missing observation, unavailable stock and zero stock are different states. The product needs an explicit display and validation policy for those categories; the sorting algorithm's special placement is not that policy.
CHAPTER 6 OF 14 · Work comparison and missing positions
6. Follow missing positions to the tail of a sparse array
The central fixture's two missing positions do not supply ordinary stored values for the controlled sort to compare. After the present entries are ordered and written back, the tail can remain missing. The length stays seven, while the own numeric indices become zero through four in this example.
For default sorting, record index zero as number 120, one as number 18, two as number 4, three as present undefined and four as present undefined. Indices five and six are missing. This complete shape is more precise than a printed list ending with several commas.
const values = [18, undefined, , 4, 120, undefined, ,];
values.sort();
// Values at 0..4: 120, 18, 4, undefined, undefined.
// Object.hasOwn(values, 5) and Object.hasOwn(values, 6) are false.
The numeric-comparator version has the same presence pattern but values 4, 18, 120 at its first three positions. The comparison rule changes those ordered numeric entries; it does not cause the two original holes to become ordinary numeric observations.
Change one hole into an explicitly present undefined value before sorting. Now there are three present undefined entries and only one missing tail position. Length is still seven. A presence-aware check detects the changed input and output even if a renderer displays both arrays identically.
Keep the no-inherited-indices assumption visible. An indexed property inherited from a prototype can make a supposedly missing position observable through property lookup. That is a different fixture. For ordinary application arrays, use clean predictable data representations rather than relying on holes to express important business states that a later operation may materialise differently.
CHAPTER 7 OF 14 · Check identity and ties
7. Compare in-place sort with a newly sorted array
Ordinary sort mutates the array and returns that same array reference. If two variables point to the central fixture, sorting through one changes the ordering seen through the other. Assigning the returned value to a new variable does not, by itself, make the original array independent.
The separate toSorted method constructs a new sorted array under its own contract. In a controlled sparse ordinary array, missing source positions are treated as undefined values for this read-through materialisation, so the new result is dense rather than retaining the same missing tail properties as sort.
For the seven-position source, a default toSorted result can contain 120, 18, 4 and four present undefined values. The original source retains its original sparse arrangement. Compare both the new result's property presence and the source-after shape; checking only length would miss the distinction.
Likewise, creating an array with Array.from before calling sort can change the representation of missing positions. That conversion has its own consumption contract. The connected Array.from lesson explains why materialisation, mapping and source observation should be treated as explicit stages rather than a neutral copying trick.
The new outer array is still a shallow arrangement of supplied values. If those values are object references, toSorted does not automatically deep-clone the objects. Reordering a new sequence and making every nested object independent are different requirements.
For a website, decide whether source order belongs to shared application state or only to a local view. Choose an in-place or new-result operation accordingly, then test the representation changes as well. A convenient promise not to mutate the outer source does not establish preservation of holes, deep independence or a correct reader-facing data policy.
CHAPTER 8 OF 14 · Check identity and ties
8. Use stability without turning equal keys into equal records
Under a consistent comparison, the ordinary stable sorting requirement preserves relative order among entries that compare equal. That is useful when two catalogue records have the same numeric quantity but carry different identifiers. Their comparison tie does not erase either record.
Create records Cedar with quantity four, Birch with quantity two and Elm with quantity four, in that input order. A consistent quantity comparator places Birch first, then Cedar and Elm in their original relative order. The two quantity-four records remain distinct objects with different identifiers.
Change the original order of the tied records to Elm before Cedar. A fresh quantity sort preserves that changed tie order. The sorter has not decided which name is intrinsically more important; it preserves the prior relationship under an equal comparison key.
If the product needs a secondary alphabetical or identifier rule, define that rule explicitly. Stability is not a substitute for a required secondary key. It retains the input relationship among ties, and that input relationship might itself come from another source or an earlier explicit ordering step.
A mixed primitive example uses the number four and the string "4". They can compare equal under their default string forms while retaining different types. Stable treatment of that tie does not validate them as interchangeable quantities or prove that converting between their types would preserve the application's meaning.
The Algorithm Design root introduces consistency, stability and key choice at a broad level. This guide adds the concrete ordinary JavaScript contracts for default representations, undefined values and sparse slots. Use the broader root for algorithm-selection reasoning, and keep this specific value-and-presence trace for diagnosing the built-in array operation.
CHAPTER 9 OF 14 · Connect sorting to the reader task
9. Define an invalid-data policy before sorting
A quantity list can contain NaN, blank strings, symbolic codes or other values outside the chosen finite numeric domain. A subtraction comparator does not automatically establish a meaningful order over every such category. Before sorting, decide what the application accepts and how it reports rejected or missing data.
In ordinary comparator processing, a returned NaN is treated as a zero comparison result. That does not mean the two inputs are equal quantities. It means the comparator failed to express the intended distinction at that comparison boundary. A dataset with invalid values can therefore violate the consistency assumptions needed for a useful ordering.
For a controlled diagnostic, compare a valid quantity against a value whose numeric interpretation is NaN, then compare two different valid quantities. If the invalid entry is treated as tied to both, a naive equality interpretation can contradict the numerical difference between the valid entries. A stable-sort label cannot repair that broken data contract.
An explicit policy might reject the row, separate unavailable observations into a distinct group or sort validated records with a deliberate missingness key. Choose according to the website's actual task. Do not silently turn blank text into zero or remove a record merely because that makes the output look ordered.
For a concrete check, compare a supplied numeric zero with an empty text field. Converting the empty string through Number can produce zero, but that conversion does not establish that the visitor supplied a measured zero. Keep the raw input and its validation outcome available until the application has deliberately decided whether blank means missing, invalid or a permitted default. Sorting the converted numbers cannot recover a distinction discarded earlier, so the important repair belongs at the input boundary.
If sorting records, a present record with an absent quantity field is different from an array element that is itself undefined. The comparator receives the record object and must apply the application's field policy. The built-in special handling of undefined array elements does not automatically implement missing-field handling inside every object.
The practical check starts before the sort: count accepted records, rejected records and explicitly missing observations. After sorting, preserve those counts and identities under the stated policy. An ordered-looking output is not evidence of correctness if the application silently changed meanings, lost records or treated invalid observations as measured quantities.
A throwing comparator needs a separate failure record. If its code increments a counter before throwing, that effect remains observable even though sort does not return normally. Do not infer that every part of application state was rolled back merely because there is no successful returned array. Conversely, do not invent a particular partially reordered array without checking the actual failure stage and input contract.
The practical design is a comparator whose required keys are already validated and whose comparisons do not alter the source or external state. If obtaining a key can run a getter, consider a deliberate extraction step with its own consistency checks. This makes the ordering relation easier to test and prevents a changing comparison key from undermining conclusions drawn from an earlier friendly fixture.
CHAPTER 10 OF 14 · Connect sorting to the reader task
10. Choose quantity order and symbolic-code order deliberately
A catalogue can contain numerical quantities and symbolic item codes that both look like digits. Their legitimate comparison rules may differ. A quantity field supports arithmetic relationships. A code can preserve leading zeros or a fixed representation whose meaning does not reduce to its numeric value.
For an original code fixture, use "004", "04" and "4". A numeric conversion can make them equal as quantities, but that does not establish that the application may merge the corresponding catalogue identities. Preserve the original codes while choosing an explicitly documented ordering key.
A text-oriented comparison can preserve distinctions while still failing to match the product's expected natural ordering. The correct question is what users need to find and which identifiers the system actually recognises. There is no universal instruction to sort every digit-containing string numerically.
For the quantity view, keep validated finite numbers and a numerical comparator. For a code view, choose the representation and comparison policy appropriate to those codes. The same underlying records can support two explicitly named views without pretending that their ordering requirements are identical.
This section extends the broad Algorithm Design warning about key definitions without reproducing its general sorting lesson. The additional JavaScript issue is that an omitted comparator already selects a particular default relation. Omitting a function is an active contract choice, not an instruction for the runtime to infer the catalogue's semantic intent.
Test boundary pairs that expose the chosen rule. Include equal quantities with different identifiers, different representations of a numeric-looking code and at least one pair where default and numeric order disagree. Those cases make a future refactor reviewable and prevent a friendly initial dataset from hiding the real requirement.
CHAPTER 11 OF 14 · Connect sorting to the reader task
11. Keep sorted data separate from the displayed journey
A correct sorted array does not prove that the page displays the same sequence. A renderer can reuse stale state, place items through a different layout order or attach actions to the wrong record after indices change. The array contract is one stage in the reader's actual journey.
Use stable record identifiers when checking displayed cards and their actions. After sorting Cedar and Birch, clicking the first card should act on the record shown there under the application's design. An event closure retaining an earlier index can refer to a different item after the shared array was mutated.
The current-target and delayed-action guide develops identity capture through event dispatch and deferred work. Here the connection is narrower: an index is a position in a particular sequence, and sorting changes positions. It should not be treated as a permanent record identity merely because it worked before reordering.
Visual placement is another boundary. The CSS Grid placement specialist distinguishes visual arrangement from document order. If a catalogue uses that layout, verify both the sorted data sequence and the actual accessible reading and interaction sequence instead of assuming one establishes the other.
Change the central fixture into labelled rows with unavailable quantities. A blank output cell should still explain the unavailable state if the product requires that meaning. Rendering both holes and undefined as silence may hide an important distinction that the data audit carefully preserved.
For a practical end-to-end check, name the source order, sorted record identifiers, rendered order and action target. These observations connect the language-level result to the visitor's task. A locally passing comparator fixture remains valuable, but its scope should not expand into an unperformed claim about the whole website interface.
CHAPTER 12 OF 14 · Test and transfer
12. Test invariants rather than one engine's comparison itinerary
Use fresh copies of the central fixture for default and numeric sorting. Assert the ordered numeric values, the two present undefined entries, the missing tail properties and unchanged length. Also assert that sort returns the exact source array reference. These checks expose the contract that a plain printed output would conceal.
For a supplied comparator, log argument categories and assert that undefined is not passed in the controlled fixture. Avoid requiring one exact pair sequence or comparison count. Different compliant implementations can choose different comparison itineraries while satisfying the same consistent ordering and stability requirements.
Test the new-result method separately. Check that toSorted returns a different array, leaves the source's own indexed properties unchanged and produces the expected dense undefined entries for this sparse source. A shared nested object fixture can verify that new outer identity does not imply deep cloning.
Add a stable-record test with two equal quantities and distinct identifiers. Preserve their input relative order under a consistent comparator. Then add direct comparator checks for negative, positive and zero results, rather than assuming that one successful three-item sort proves the comparison relation is valid.
The changed-domain tests should fail or separate invalid records under the chosen application policy. They should not merely assert that JavaScript returned some array without throwing. A valid numeric list and an array containing an invalid quantity represent different requirements.
These controlled checks exercise language behaviour in the recorded JavaScript runtime. They do not benchmark sorting complexity, certify every engine's optimisation or verify a browser's rendered reading order. Keep those claims separate and add actual interface evidence only when the corresponding page and user journey have been exercised.
CHAPTER 13 OF 14 · Test and transfer
13. Transfer the rule to negative and decimal quantities
Change the numerical values to negative two, negative three and positive four. Default string comparison can place negative two before negative three because the first minus signs match and the next code units compare as 2 before 3. Numeric ascending order instead places negative three before negative two.
This case exposes why a default string order cannot be rescued by a vague rule about shorter numbers appearing first. The controlling relation is the comparison representation. The minus sign participates in the string while the numeric comparator evaluates the quantities' mathematical order.
Now use decimal values 2.5, 11.2 and 3.1. The default order places 11.2 before 2.5 and 3.1 in this fixture, whereas numeric ascending order is 2.5, 3.1, 11.2. The decimal point does not cause the omitted comparator to become an arithmetic comparison.
Add one present undefined entry and one missing slot to a fresh decimal fixture. Predict the non-undefined ordering under each comparator, then place undefined and the missing position according to their separate contracts. The exercise requires combining the distinctions rather than answering only the numeric part.
For an independent check, replace the decimal values with three validated quantities of your own, including a negative pair with equal printed length. Write both predicted orders, count present properties and explain why the comparator should never receive the actual undefined entry in this ordinary fixture.
Finally change the requirement from quantity order to a labelled report grouping unavailable observations. Design that grouping explicitly before sorting the accepted quantities. This prevents the language mechanism's treatment of undefined from becoming an accidental product policy for missing evidence, unavailable stock or a field that was never supplied.
CHAPTER 14 OF 14 · Test and transfer
14. Report the comparison rule and the final shape
A precise report names ordinary Array.prototype.sort, the chosen comparator or its omission, the accepted value domain and whether the operation mutates the source. For a sparse fixture it also records length, own indexed properties and the distinction between present undefined entries and missing positions.
For the central default case, report 120, 18 and 4 as the ordered numbers, then two present undefined entries and two missing tail positions. For the numeric case, report 4, 18 and 120 with the same presence pattern. That is a complete result under the stated clean-prototype assumptions.
If a result uses toSorted or an Array.from materialisation, report the new representation rather than importing sort's hole-preservation expectation. An array can keep the same length while changing which positions are present. That difference can affect later iteration and display even when the visible cells look similar.
When records carry invalid or missing fields, identify the application policy before describing the output as numerically sorted. State whether records were rejected, separated or compared through explicit keys. Preserve identities and counts so an attractive ordering cannot conceal lost or silently reinterpreted data.
To practise independently, build a seven-position array with three quantities, two explicit undefined values and two holes. Predict default, numeric and new-result shapes before running them. Then explain which assertions concern language behaviour and which would need a separate browser journey check.
The useful habit is to ask what is being compared and what is actually present. Once comparison strings, numeric relations, undefined handling and property presence are separate, a surprising catalogue order becomes a traceable decision. The author can then select the rule and representation that fit the reader's task.
Continue through the verified reading route
Algorithm Design: ordering requirements and stability
Algorithm Design: ordering requirements and stability. Use the broader guide for key consistency and algorithm-selection reasoning.
Event owners and deferred actions
Event owners and deferred actions. Keep stable record identity separate from a position changed by sorting.
CSS Grid visual and document order
CSS Grid visual and document order. Check the rendered reading sequence separately from the sorted data sequence.
Array.from consumption and materialisation
Array.from consumption and materialisation. Trace when a conversion obtains values and turns missing positions into present undefined entries.
Frequently asked questions
Why does 120 appear before 18 in the default sort?
Their default comparison strings begin with the same first character, then 2 precedes 8. The operation is not comparing their numerical magnitudes. A suitable numeric comparator changes that relation for a validated numeric domain.
Does default sorting turn stored numbers into strings?
Using string forms for comparison does not replace every stored numeric value with a string. Inspect value types separately. A mixed array can retain its original numbers and strings after reordering.
Can my comparator move undefined entries to the front?
Actual undefined array elements receive special handling before ordinary comparator calls in this contract. If the product requires another missing-data policy, represent and process it explicitly rather than assuming an undefined branch in the comparator will run.
Is a missing slot the same as a present undefined value?
No. Both can read as undefined under the clean fixture, but property presence differs. The sparse sort trace retains missing tail properties, while materialisation through another operation can create present undefined entries.
Does sort return an independent array?
Ordinary sort changes and returns the same array. A distinct new-result method has its own representation contract, and even a new outer array can still share nested object references. Test the exact boundary the application needs.
Does stable sorting fix an inconsistent comparator?
Stability preserves relative order among equal comparison keys under the appropriate ordering contract. It does not validate contradictory comparisons, repair invalid quantities or decide a missing-data policy on the application's behalf.
Authoritative sources and further reading
ECMAScript language specification: Array.prototype.sort. The normative ordinary-array comparison, sparse property and mutation contract.
ECMAScript language specification: Array.prototype.toSorted. New sorted arrays use read-through-hole materialisation under a distinct contract.
ECMAScript language specification: typed-array sorting. The typed-array comparison is a separate numeric-default method.
MDN: Array.prototype.sort. API documentation for numeric comparison, stability and undefined versus missing positions.
Return to the Websites subject guide, The Gold Standard of Education, or the How X Works hub.