whatstheoutput_

#36: [10, 9, 1].sort()

Topic: arrays · Difficulty: ★

const arr = [10, 9, 1];
console.log(arr.sort());

Output

[ 1, 10, 9 ]

Why

Array.prototype.sort() with no comparator converts every element to a string and compares them by UTF-16 code unit — it does NOT compare numerically. As strings, '10' comes before '9' because '1' sorts before '9' character by character. So numeric [10, 9, 1] sorts to [1, 10, 9], not [1, 9, 10]. To sort numbers correctly, always pass a comparator: arr.sort((a, b) => a - b).

More arrays puzzles

Play today's puzzle →