Reputation: 132374
I found a bug in a script that was written, and I'm having troubles figuring out exactly what is causing the issues. Specifically:
"49px" < 50 === false
There's two different conversions I can think of here:
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 does this evaluate to false? What exactly is happening here?
Upvotes: 7
Views: 118
Reputation: 78183
If one operand is a number and another operand is a string, then the string is converted to a number and then the comparison is made.
If the string cannot be converted to a number, it gets converted to NaN
, and the comparison always returns false
.
Upvotes: 10
Reputation: 492
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
.
Upvotes: 3