The default string sort trap
[...nums] makes a copy so each line starts from the same order. localeCompare puts apple next to Apple the way a dictionary would; undefined always goes last.
sort reorders an array in place and, without a comparator, sorts everything as text (so [10, 1, 5] becomes [1, 10, 5]); pass (a, b) => a - b for numbers, use toSorted and toReversed to get a sorted copy, and rely on sort being stable since ES2019.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Sort ["pear", "Fig", "apple"] alphabetically, ignoring capital letters, without changing the original.
Sort products by price (low to high), and products with the same price by name.
Explain it without notes
Why does [10, 1, 5].sort() return [1, 10, 5]?
How does a comparator function work?
What does it mean that sort is stable, and why is it useful?
What is the difference between sort and toSorted?
Console
(nothing was printed)Expected console output
[ 1, 10, 100, 25, 5 ]
[ 1, 5, 10, 25, 100 ]
[ 100, 25, 10, 5, 1 ]
[ 'Apple', 'apple', 'banana', 'cherry' ]
[ 'apple', 'Apple', 'banana', 'cherry' ]
[ 1, 3, undefined ]