Search code examples
javascripttypescoerciontype-coercion

Bug in Javascript type coercion


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?


Solution

  • 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.