"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does \"11\" Compare as Less Than \"3\" in JavaScript?

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

Published on 2024-11-04
Browse:688

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'

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'

Here are some additional examples to illustrate this behavior:

  • '31'
  • '31'
  • '31'

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:

 '11' 
Release Statement This article is reprinted at: 1729224258 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3