Home > Web Front-end > JS Tutorial > Why Does \'11\' Compare as Less Than \'3\' in JavaScript?

Why Does \'11\' Compare as Less Than \'3\' in JavaScript?

Mary-Kate Olsen
Release: 2024-10-18 12:58:02
Original
1081 people have browsed it

Why Does

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:

  • '31' < '3': false (the first character of '31' is greater than the first character of '3')
  • '31' < '32': true (the first character of '31' is less than the first character of '32')
  • '31' < '30': false (the first character of '31' is greater than the first character of '30')

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template