29
if ('11' < '3') alert('true');

It's obvious that it's not comparing them by length but by encoding instead. However, I don't understand how it works. I need some explanation :-)

jilseego
  • 1,083
  • 5
  • 13
  • 21

6 Answers6

57

Strings are compared lexicographicaly. i.e. character by character until they are not equal or there aren't any characters left to compare. The first character of '11' is less than the first character of '3'.

> '11' < '3'
true
> '31' < '3'
false
> '31' < '32'
true
> '31' < '30'
false

If we use letters then, since b is not less than a, abc is not less than aaa, but since c is less than d, abc is less than abd.

> 'abc' < 'aaa'
false
> 'abc' < 'abd'
true

You can explicitly convert strings to numbers:

> +'11' < '3'
false
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

By default, JavaScript will compare two strings by each character's ordinal value; much like how strcmp() works in C.

To make your comparison work, you can cast either side to a number to tell the interpreter your intentions of numeric comparison:

Number('11') < '3' // false
+'11' < '3' // false, using + to coerce '11' to a numeric

'11' < Number('3') // false
'11' < +'3' // false
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
4

In Many Programming languages Strings are compared as lexicographically. You can check Alphabetical order

Ramesh Kotha
  • 8,266
  • 17
  • 66
  • 90
3

It compares by each character, the following will be false:

if ('41' < '3') alert('true');

Since 4 is not less than 3. So essentially your comparison boiled down to this:

if ('1' < '3') alert('true'); // true
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2

'1' < '3' and since the first character is the "most significant character" (not that this term makes any sense). Any following characters will not be compared anymore.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • I guess OP might not know ASCII. Therefore, I believe it may be helpful if a sorted list of characters is included. Here is it: [ASCII](http://en.wikipedia.org/wiki/ASCII). – Haozhun Jun 02 '12 at 14:37
0

It has been treated as string comparision. So 1 < 3 (1st chars of two strings) then string 11 preceeds string 3

Rajasekhar
  • 894
  • 5
  • 13
  • 25