Why is string "11" less than string "3"?
comparison, javascript, string
Solution
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
Problem
``` 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 :-)