Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why eval("475957E-8905") == "475957E-8905" is true?

I made a program with nodeJs which generate code such as

eval("XXXXXX") == "XXXXXX"

It's working pretty well, but at a moment he gave me this :

    eval("475957E-8905") == "475957E-8905"

I tested it with Firebug, and the result is true .But I don't really understand why.

Of course, eval("475957E-8905") return 0 but why 0 == "475957E-8905" ?

like image 354
Pyrofoux Avatar asked Dec 15 '22 01:12

Pyrofoux


2 Answers

There are two pieces to this puzzle: floating-point numbers and type-insensitive comparison using ==.

First, 475957E-8905 evaluates as the floating point number 475957 * 10 ^ -8905, which is incredibly small; in floating-point terms, it's the same as 0 due to the precision limitations of javascript. So, eval("475957E-8905") returns 0.

Now, for the second piece of the puzzle.

The == means that the types don't have to match, so nodejs (like any JavaScript engine) tries to convert one of them so it can compare them.

Since eval("475957E-8905") returned 0, it tries to convert "475957E-8905" to an integer as well. As we have seen, that is also 0. Thus, the comparison is 0 == 0, which is true.

Note that the same thing happens if you do eval("3") == "3" or eval("3") == 3 -- in each case, the strings are converted to numbers and compared.

Avoiding this problem

You can force a type-sensitive comparison like this:

eval("475957E-8905") === "475957E-8905"

which returns false, because the === tells the javascript engine to return true only if the types and the values both match.

like image 198
elixenide Avatar answered Jan 06 '23 03:01

elixenide


Javascript has to convert your string, "475957E-8905", to a number in order to compare them. When it does that, it converts "475957E-8905" to 0 as well. So, 0 == 0;

As you can see:

"475957E-8905" == 0

Is true. Basically you eval statement "475957E-8905" into a number, and then the other "475957E-8905" is being converted to a number for comparison. In the end, the exact same conversion process has happened to both of them and they are both 0.

like image 26
Damien Black Avatar answered Jan 06 '23 05:01

Damien Black