Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.6 — Sorting
JavaScript · Example 2 of 3 ES2023+

sort mutates; toSorted and toReversed copy

sort returned the very same array it changed. toSorted and toReversed (ES2023) leave scores alone; reverse changes it.

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.

01

Sort ["pear", "Fig", "apple"] alphabetically, ignoring capital letters, without changing the original.

02

Sort products by price (low to high), and products with the same price by name.

Explain it without notes

01

Why does [10, 1, 5].sort() return [1, 10, 5]?

02

How does a comparator function work?

03

What does it mean that sort is stable, and why is it useful?

04

What is the difference between sort and toSorted?

sort mutates; toSorted and toReversed copy ES2023+

Console

(nothing was printed)

Expected console output

true [ 1, 2, 3 ]
[ 40, 90, 70 ] [ 90, 70, 40 ]
[ 70, 90, 40 ] [ 40, 90, 70 ]
[ 70, 90, 40 ]