-1

When I am running the mentioned code. What is the reason behind giving it false and not the second one is it related to ascii value or something else I am Unable to get it. Can anyone explain this?

console.log('2' < '123');
console.log(2 < '123');
DarkBee
  • 16,592
  • 6
  • 46
  • 58
Anurag Yadav
  • 79
  • 10
  • 1
    In the first case, strings are compared lexicographically. Meaning character by character. In the second case the 123 is converted to number – NazaRN Dec 15 '22 at 11:12
  • 1
    @Etheryte: The question marked as the dupe doesn't contain any reference about the `2 < '123'` case – DarkBee Dec 15 '22 at 11:19
  • dupe regarding string/number comparisons: [Javascript string/integer comparisons](https://stackoverflow.com/questions/5630123/javascript-string-integer-comparisons) – pilchard Dec 15 '22 at 11:45
  • @DarkBee Yes it does, if you take the time to read more than just the first answer. – Etheryte Dec 15 '22 at 12:07
  • @Etheryte I did read more than just the first answer. From what I can read, the only thing being said bout number to number comparison is `to cast either side to a number`, but in this question both sides are already numbers... – DarkBee Dec 15 '22 at 12:28
  • Should I delete it? – Anurag Yadav Dec 15 '22 at 12:39

1 Answers1

1

The rules for < say that:

  • (Step 3) If you compare a string to a string: Compare them lexically.

  • (Starting from Step 4c) If you compare a number to a string: Convert the string to a number, then compare them numerically.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 2
    [Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than#description) for additional reference – Rajesh Dec 15 '22 at 11:15