How do strings behave in JavaScript?
The reason is that the comparison operators turn their operands into simple values and then compare them, and when both sides are strings the comparison is done letter by letter. Each character is compared by its code unit value, and the first difference decides the result. When one string is the beginning of the other, the shorter string sorts first.
The result that surprises people is the treatment of case. Uppercase letters have lower code unit values than lowercase letters, so the comparison puts every capital letter before every small letter. That is why comparing with the greater-than operator gives you an order that does not match what people expect from an alphabetical list.
The same thing happens with punctuation and digits. The digits come before the uppercase letters, and the punctuation comes before the digits, and all of that follows the numeric code points rather than any human idea of alphabetical order.
For real text, use the localeCompare method. It compares two strings using the rules of a language, so case, accents, and language-specific ordering are handled in the way that a reader expects. You can pass a locale to control the language and an options object to control how strict the comparison is, so a comparison can ignore case or ignore accents when you ask for that.
One more point is worth making in an interview. Comparing strings with the equality operators compares the content and not the identity, and it does not change between types. A string is never equal to a number, even when the number looks like the same digits, so the comparison operators and the equality operators behave differently here. The next question in this topic looks at what happens when you try to change a string.