const list = [3, 11]
list.sort()
console.log(list[0] < list[1])
logs `false`. JavaScript doesn't "think" anything but its native sort function doesn't do what many people expect it would when called on a list of pure numbers.
If you found this behavior intuitive and unsurprising the first time you saw it, then your brain works differently than mine.
If this happens to be new to you (congrats on being one of today's 10,000), the reason is that JavaScript sorts by converting all elements to UTF-16 strings, except for `undefined` for some reason, which always sorts last. The MDN docs have a very clear explanation. I have been unable to find a historical explanation of why this choice was made, but I presume the initial JS v1 author either had a good reason or just really didn't expect that their language would outlive the job for which it was written.
If this is a bug for you, you can provide a comparison function explicitly and the typical is something like:
list.sort((a,b)=>a-b)
Somewhat puzzlingly, this will "work" even on lists with mixed number and string like:
Because JavaScript goes out of its way to make comparisons like 3 < "11" or "3" < 11 work in the numeric domain. JS only uses string comparison when both sides are strings.
I do not think it's intuitive. The reason it works for mixed arrays is that the minus operator coerce operands to numbers. However if the strings fail to convert to a numeric value, the output is arguably even less sensible. I'd imagine that's why it is.
It may have been thought that js would be more likely to be dealing with strings arrays.
If you found this behavior intuitive and unsurprising the first time you saw it, then your brain works differently than mine.
If this happens to be new to you (congrats on being one of today's 10,000), the reason is that JavaScript sorts by converting all elements to UTF-16 strings, except for `undefined` for some reason, which always sorts last. The MDN docs have a very clear explanation. I have been unable to find a historical explanation of why this choice was made, but I presume the initial JS v1 author either had a good reason or just really didn't expect that their language would outlive the job for which it was written.
If this is a bug for you, you can provide a comparison function explicitly and the typical is something like:
Somewhat puzzlingly, this will "work" even on lists with mixed number and string like: Because JavaScript goes out of its way to make comparisons like 3 < "11" or "3" < 11 work in the numeric domain. JS only uses string comparison when both sides are strings.