What kind of Javascript type conversions are happening here?

I found an error in the script that was written, and I am having trouble figuring out what causes the problems. In particular:

"49px" < 50 === false 

There can be two different conversions:

 49 < 50 === true "49px" < "50" === true "49" < 50 === true // just for the hell of it 

I fixed it with

 parseInt("49px") < 50 === true 

So why is this evaluating to false? What exactly is going on here?

+7
source share
2 answers

If one operand is a number and the other operand is a string, then the string is converted to a number , and then the comparison is performed.

If the string cannot be converted to a number, it is converted to NaN , and the comparison always returns false .

+10
source

When javascript is asked to compare a number with something else, it tries to convert that "something else" to a number. In this case, "49px" evaluates to NaN , so NaN < 50 is false .

+3
source

All Articles