javascriptcomparisontruthiness

Using Comparison (< >) Operators With Non-Numeric Strings in Javascript


I'm trying to figure out exactly what is happening when I compare a number to a non numeric string in javascript with the < or > operator.

When I make the following comparisons in JS

console.log(0 > "y")
console.log(5000 > "y")
console.log(-3 > "y")
console.log("y" > 3)

it always evaluates to false.

What is happening to each side in this comparison? What is y being turned into? What about the number?


Solution

  • When using comparison operators with operands of different types, primitive values are coerced as numbers. In this case, for the purpose of comparison "y" becomes NaN, which is neither greater than, less than or equal to any number.