I delved into Twitter again and found this little tweet by Nico Castro. This is a quick one, but it does need a fair bit of explanation to clarify things.
So what’s going on here? Why is the small ‘a’ greater than capital ‘Z’, but at the same time capital ‘A’ isn’t greater than capital ‘Z’?
Nico is on the right track, ASCII has a lot to do with it, but it’s a teeny tiny bit more complex than that… Let’s take another look at those two statements:
"a" > "Z" // true
"A" > "Z" // false
So, as I said, there is some focus on the ASCII component of the strings that comes into play.
Let’s replace the strings with their ASCII numeric equivalents. Once we do, we see something that instantly clicks:
97 > 90 // "a" > "Z" == true!
65 > 90 // "A" > "Z" == false!
Here are three more examples…
"ab" > "ac" // false
"ab" > "a" // true
"ate" > "are" // true
Second example is slightly trickier. We have a two character-long string compared against a single character. What happens there?
So “a” which we know is the same as [“a”] is also technically equivalent to [“a”, undefined]!
In short, when comparing strings with greater-than or lesser-than operators, the shorter string will be “appended” with undefined instances when converted to an array until both arrays are of equal length before doing the final series of comparisons. And because undefined is a falsy value, when compared, the undefined gets coerced to 0.
With all that said and done, we finally end up with: [97,98] (“ab”) and [97,0] (“a”). Comparing the two arrays, We get the zeroth elements not satisfying the > operator, but the first elements do, so true is returned.
Finally, we compare “ate” with “are”. When both strings are converted to numeric arrays for comparison we have [97, 116, 101] and [97, 114, 101] . The rest is a foregone conclusion:
Index 0; is 97 > 97? No, move onto index 1.
Index 0; is 116 > 114? Yes! Ding Ding Ding! Stop processing and return true.