Home >Web Front-end >JS Tutorial >Why Does \'11\' Compare as Less Than \'3\' in JavaScript?
String Comparison Anomalies: Why "11" Is Less Than "3" in JavaScript
JavaScript's string comparison behavior can be counterintuitive at times. One such example is the inequality '11' < '3', which surprisingly returns true.
In JavaScript, strings are compared lexicographically character by character, from left to right. When the characters are different, the comparison is based on their Unicode code points. The ASCII code for '1' is 49, while that for '3' is 51. Therefore, the first character of '11' (with a code point of 49) is less than the first character of '3' (with a code point of 51), resulting in the inequality '11' < '3'.
Here are some additional examples to illustrate this behavior:
It's important to note that the same comparison rules apply to letters. If 'b' is not less than 'a', 'abc' cannot be less than 'aaa'. However, 'c' is less than 'd', so 'abc' is less than 'abd'.
To avoid such anomalies when comparing strings as numbers, it's recommended to explicitly convert them using the ' ' operator:
<code class="js">+'11' < '3' // false</code>
The above is the detailed content of Why Does '11' Compare as Less Than '3' in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!