sort Without A Comparator Compares As Strings

Default sort compares elements as UTF-16 code unit strings, so numbers sort lexicographically; numeric order needs an explicit comparator.

JavascriptData Integrity

Code

javascriptsnippet
21 lines
// sort without a comparator converts elements to strings and compares UTF-16 code units:
// numbers order lexicographically, not numerically
const scores = [80, 9, 100, 25, 3];
console.log('default :', scores.slice().sort().join(','));
console.log('numeric :', scores.slice().sort((a, b) => a - b).join(','));

// String arrays: default order is by code unit (uppercase before lowercase), localeCompare follows language rules
const names = ['Zoe', 'adam', 'Bea'];
console.log('names default      :', names.slice().sort().join(','));
console.log('names localeCompare:', names.slice().sort((a, b) => a.localeCompare(b)).join(','));

// undefined is exempt from comparison: any comparator sends it to the end of the array
const withUndefined = [3, undefined, 1, undefined];
console.log(
  'undefined sinks:',
  withUndefined.slice().sort((a, b) => a - b).map((v) => String(v)).join(','),
);

// sort mutates the array in place: slice() first when the original must survive
const sorted = scores.slice().sort((a, b) => a - b);
console.log('sorted copy:', sorted.join(','), '| original intact:', scores.join(','));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

default : 100,25,3,80,9
numeric : 3,9,25,80,100
names default      : Bea,Zoe,adam
names localeCompare: adam,Bea,Zoe
undefined sinks: 1,3,undefined,undefined
sorted copy: 3,9,25,80,100 | original intact: 80,9,100,25,3

How the snippet works

Module-level bindings hold the data — scores, names, withUndefined, sorted — with no function scope in between.

Using it

Running the file prints labeled results such as default :, numeric :, names default : — each operation’s effect is visible in the output.

Key statements

const sorted = scores.slice().sort((a, b) => a - b);

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. Its state lives in module-level bindings: `scores`, `names`, `withUndefined`.