-1

Can someone explain why the condition '12:34' < '123:45' is false?

console.log('12:34' < '123:45' ? 'true' : 'false')
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Rodrigo Guariento
  • 137
  • 1
  • 1
  • 13
  • 4
    (Why) do you expect it to be true? – B001ᛦ Aug 03 '20 at 21:45
  • Use rather `'12:34'.localeCompare('123:45')` which will give you `-1` as result, meaning that `"12:34"` comes **before** `"123:45"`. [MDN localeCompare](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) – Roko C. Buljan Aug 03 '20 at 21:49

4 Answers4

6

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));
OmG
  • 18,337
  • 10
  • 57
  • 90
1

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?

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
  • _“There's not only numbers in the string so it will compare with String not Number”_ — no string is compared like a number, regardless of what characters it contains. – Sebastian Simon Aug 03 '20 at 22:17
1

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.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Fritzdultimate
  • 372
  • 2
  • 11
1

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.

Jason Melton
  • 46
  • 1
  • 4