7

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?

asked May 13, 2011 at 0:30
5
  • 1
    Check out the Abstract Relational Comparison Algorithm... Commented May 13, 2011 at 0:41
  • Fix is inadequate. Number("49px") happens, parseInt/Float are behaving differently Commented May 13, 2011 at 2:36
  • 1
    y u no specifiy a radix in your parse int?! developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… do it now while it's not too late! Commented May 13, 2011 at 2:42
  • @user422039: Look at the documentation for parseInt, it is working properly and as expected. Number("49px") does not call parseInt, it interprets the string as an exact number. Commented May 13, 2011 at 3:00
  • reread my comment, original variant code does not use any of parseXXX function. Commented May 13, 2011 at 15:33

2 Answers 2

10

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.

Matthew Scharley
134k55 gold badges199 silver badges225 bronze badges
answered May 13, 2011 at 0:38
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Šime Vidas
187k66 gold badges290 silver badges392 bronze badges
answered May 13, 2011 at 0:42

1 Comment

darn, just a few minutes too late!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.