2

While working in my JS code today, I found the following situation and can not explain myself what should be the correct output ?

'sachin' > 2 // False

'sachin' < 2 // False

'sachin' == 2 // False

I expect result of either of < or > should be true. What am I missing ?

2
  • 1
    Does that comparison really make sense to you at all Commented May 5, 2014 at 17:52
  • @adeneo I know it does not make sense in code but I want to understand what browser will do when it encounters such a statement. Commented May 5, 2014 at 17:57

1 Answer 1

4

When the runtime attempts to convert 'sachin' to a number, it will fail and end up as NaN. That special constant results in false for any comparison to any other numeric value. The NaN constant ("Not A Number") is not equal to any other value, nor is it less than or greater than any other value.

edit — the ==, <, and > operators all "prefer" numbers to strings. If one operand is a number and the other a string, they'll always try to interpret the string as a number. It doesn't matter what order the operands appear in; what matters is the operand types.

(Strictly speaking, the results of < and > when NaN is involved are supposed to be undefined, according to the spec, but Firefox seems to give false instead.)

Sign up to request clarification or add additional context in comments.

4 Comments

Does that mean runtime tries to convert left operator to the type of right hand operator ?
@blunderboy no, it has to do with the types of values involved, and the particular operator. I'll extend the answer (once I double-check the language spec to make sure my memory's OK :)
@blunderboy OK sorry I updated the answer - what I had written about == was incorrect; I think I was thinking about the + operator.
Thanks for the explanation!! I will go and read some article on type conversion in JS to make things more clear to me..

Your Answer

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.