-3

Since "string" is a non-empty string, shouldn't it return true? How exactly does this comparison work?

Lethal
  • 61
  • 1
  • 5

2 Answers2

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.

Comparison Operators

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