Comparing strings in javascript

I have the following script

document.write("12" < "2"); 

which returns true. Why? The documentation says that javascript compares strings numerically, but I don't see how "12" is less than "2".

+4
source share
4 answers

JavaScript compares character strings by character until one of the characters is different.

1 is less than 2, so it stops comparing after the first character.

+10
source

I suppose he does a lexicographic comparison - the first char in line one is equal to '1', which is less than the first char of line two, which is equal to '2'. More about lexicographic order here: http://en.wikipedia.org/wiki/Lexicographical_order

+4
source

This is because the first character "12" is 1 , which precedes "2" ; and string comparison in JavaScript is lexically / alphabetically, not numerically. Although it looks partially numeric, since 1 sorted ahead of 2 .

However, you can simply compare numbers as numbers:

 document.write(parseFloat("12") < parseFloat("2")); 
+3
source

Try:

 document.write(parseInt("12") < parseInt("2")); 
-2
source

Source: https://habr.com/ru/post/1484738/


All Articles