JavaScript

array sort in JavaScript

JavaScriptArrayssortingintermediate

What this snippet does

Without a comparator, sort() converts to strings — '10' < '2' alphabetically, so always pass (a, b) => a - b for numbers.

Expected output

[ 10, 2, 20, 30, 4 ]
[ 2, 4, 10, 20, 30 ]
[ 30, 20, 10, 4, 2 ]

Why practise typing this

Typing arrays code builds muscle memory for the symbols and indentation JavaScript uses most, which prose-based typing tests never cover. DevType measures your words per minute and accuracy on this snippet and tracks the individual characters you mistype, so later lessons can target them.

More JavaScript practice

Browse all JavaScript snippets →