Question

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" ?

Was it helpful?

Solution

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.

OTHER TIPS

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.

use === to compare the type as well, for further information:

JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two objects are strictly equal if they refer to the same Object.
  • Null and Undefined types are == (but not ===). [I.e. Null==Undefined (but not Null===Undefined)]

check this documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top