Andriy Simonov Andriy Simonov - 9 months ago 32
Javascript Question

Coercion of a number and a string in comparison operators

I run the following code in a browser console (FireFox and Chromium):

console.log('v' > 5);
console.log('v' < 5);


Both statements return false. It actually comes as no surprise in case of
'v' < 5
, but why does
'v' > 5
return false? As far as I understand 5 gets converted to a string that is compared to
'v'
lexicographically. Did I missed something, what coercion rule is applied here?

Answer Source

The coercion is in the other direction. 'v' is coerced to number, yielding NaN, which will make any comparison with another number return false.

See "What is the rationale for all comparisons returning false for IEEE754 NaN values?" on the behaviour of NaN

More details

From the EcmaScript specification:

In 12.9.3 Runtime Semantics: Evaluation the evaluation of both < and > operators is specified, with this important step:

  1. Let r be the result of performing Abstract Relational Comparison rval < lval with LeftFirst equal to false.

And,

  1. If r is undefined, return false. Otherwise, return r.

The 7.2.11 Abstract Relational Comparison starts out with:

The comparison x < y, where x and y are values, produces true, false, or undefined (which indicates that at least one operand is NaN).

NB: Note that undefined will lead to a false in the final evaluation, as stated in above quoted step 8 of section 12.9.3.

It is then required that after the primitive values have been taken from the operands, and they are not found to be both strings, they should be coerced to Number:

  1. If both px and py are Strings, then
    [...]
  2. Else
    a. Let nx be ToNumber(px).
    [...]
    c. Let ny be ToNumber(py).