Since "string" is a non-empty string, shouldn't it return true? How exactly does this comparison work?
Asked
Active
Viewed 47 times
-3
-
Why do you expect it to be true? – Felix Kling Feb 05 '18 at 08:30
2 Answers
1
When comparing a String to a Number, JavaScript tries to convert the String to a Number to make a logical comparison.
Converting "string" to a Number results in NaN, and NaN > 0 is false.
tverghis
- 957
- 8
- 31
0
This works because of typecasting and the simple fact that NaN > 0 is false.
When applying to the > operator, both operands are cast to Numbers, so that comparison becomes
Number("string") > 0 which is equivalent to NaN > 0 which evaluates to false.
enhzflep
- 12,927
- 2
- 32
- 51
Ayush Gupta
- 8,716
- 8
- 59
- 92