Can someone explain why the condition '12:34' < '123:45'
is false
?
console.log('12:34' < '123:45' ? 'true' : 'false')
Can someone explain why the condition '12:34' < '123:45'
is false
?
console.log('12:34' < '123:45' ? 'true' : 'false')
Because of the ASCII code of 3
and :
. We know that the comparison between strings will be done by the dictionary rule. Hence, as the first difference is in the third location of two strings, the ASCII code of 3
and :
will determine the result of the comparison. As the ASCII code of :
is greater than 3
, you see the false as a result. See the ASCII code of them in the following.
console.log(":".charCodeAt(0));
console.log("3".charCodeAt(0));
There's not only numbers in the string so it will compare with String not Number. When string is being compared, it starts to evaluate one by one.
So, in your case the third character is :
and 3
. Now, comparing both will result false
- 3 is greater than :
(NaN) assuming if it compares by Number in step. In fact, JavaScript compares it with charCodeAt
as mentioned in another answer. Either way, it is false
. How do you expect it to be true?
The ASCII code of "3"
is 51
, that of ":"
is 58
.
When :
comes before 3
, JavaScript assumes you’re saying 58 < 51
which is false
.
I found on this page that if you are comparing two strings, JavaScript "compares the character codes numerically one by one in the string."
The strings will be equal until the second index where one has a :
and the other has a 3
. Compare the two with charCodeAt()
.
'12:34'.charCodeAt(2) // => 58
'123:34'.charCodeAt(2) // => 51
Because :
has a larger character code, that string is considered larger than the other.