10); //true console.log("20a">"10"); //true console.log("20a">10); //false I w...">

How is a string object converted when comparing?

console.log("20">10); //true console.log("20a">"10"); //true console.log("20a">10); //false 

I want to know why the latter is returning to false. And "20a" is converted to that before the comparison.

+8
javascript
source share
3 answers

On the MDN page on comparison operators :

For relational abstract comparisons (for example, <=), the operands are first converted to primitives, then the same type before the comparison.

 console.log("20">10); //true 

This converts "20" to the number 20 and compares it. Since 20 greater than 10 , this is true.

 console.log("20a">"10"); //true 

This compares two lines. Since "20a" larger (in alphabetical order) than "10" , this is true.

 console.log("20a">10); //false 

This converts "20a" to a number. The result is NaN (do +"20a" to see it in action). NaN not greater than any number, therefore returns false.

+7
source share

The comparison algorithm in ECMAScript is described here: http://bclary.com/2004/11/07/#a-11.8.5

Comparing x <y, where x and y are values, returns true, false, or undefined (which indicates that at least one operand is NaN). Such comparisons are performed as follows:

  • Call ToPrimitive (x, tooltip number).

  • Call ToPrimitive (y, tooltip number).

3. If the type (result (1)) is a string and type (result (2)) is a string, go to step 16. (Note that this step is different from step 7 in the algorithm for the addition operator + when using and instead of or .)

4.Call ToNumber (Result (1)).

5.Call ToNumber (Result (2)).

...

Therefore, in the case of "20a">10 the javascript engine should apply ToNumber to "20a" . The complete algorithm is complex, but claims to

If the grammar cannot interpret the string as an extension of StringNumericLiteral, then the result of ToNumber is NaN.

So, you are comparing NaN with 10 , and any comparison with NaN returns false (or undefined , see comments below).

+2
source share

In the latter case, note that even "20a" < 10 returns false. This emphasizes the "20a" rating for NaN during comparison, since NaN always returns false compared to any number.

0
source share

All Articles