Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript comparison of strings

I have the following script

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

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

like image 929
Robert Rocha Avatar asked Dec 05 '22 10:12

Robert Rocha


2 Answers

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

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

like image 70
Quentin Avatar answered Jan 01 '23 02:01

Quentin


I believe it is doing a lexicographic comparison - the first char in string one is '1', which is less than the first char of string two, which is '2'. More about Lexicographic order here: http://en.wikipedia.org/wiki/Lexicographical_order

like image 42
csuwldcat Avatar answered Jan 01 '23 01:01

csuwldcat