CodePark/ questions / Arrays & objects
START PRACTICINGPRACTICE
Frontend question · JavaScript › Arrays & objects

What does this log?

console.log([10, 1, 5, 100].sort());
[ 1, 10, 100, 5 ]

The answer is [ 1, 10, 100, 5 ]. Without a compare function, sort turns each element into a string. It compares the strings by UTF-16 code units, which is like dictionary order. So '100' comes before '5', because '1' comes before '5'.

The tempting option "[ 1, 5, 10, 100 ]" is wrong because
sort does not compare numbers by default. For numbers, pass a compare function: arr.sort((a, b) => a - b).