0

I'm having this strange bug with Javascript and type coercion (automatic conversion of variables' type made by Javacript). Here is the code

console.log('23' < '3');

that is inside a file called index.js that is invoked by this simple html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello World</h1>
    <script src="index.js"></script>
</body>
</html>

What is really strange is the fact that this operation returns true and not false. I did some tests and I found that this '23 < x' operation is wrong for all 2 < x < 10. Anyone knows why this bug occurs?

  • 4
    "If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain" - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than#description – Nick Parsons Jan 09 '21 at 23:20
  • You should **never** rely on JS type coercion, due to rather unintuitive behavior. – SuperStormer Jan 09 '21 at 23:25
  • Thank you for the reply. I was following a lecture on udemy and the example was with 2 string values. I think we found a bug in a lecture of one of the most quoted udemy javascript courses – Stefano Carretti Jan 09 '21 at 23:26
  • 3
    @SuperStormer: there is no type coercion in the code. – dandavis Jan 09 '21 at 23:27
  • I want you to notice that there is no type coertion only for + and <> operators between strings. All other operations (-, /, *, ect...) triggers type coertion even if the values are 2 strings. – Stefano Carretti Jan 09 '21 at 23:34

1 Answers1

2

it is not a bug, you are comparing two strings, and the string '23' is smaller than string '3'. in string comparison, the first char is compared, if one is smaller than the other one, the comparison is terminated.

"2" is smaller than "3" also in the ASCII table (https://www.asciitable.com/), so the result is expected.

GBra 4.669
  • 1,114
  • 3
  • 5
  • 19