Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how a string object transforms when compared?

Tags:

javascript

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

I want to know why the last one turns false. And "20a" transforms to what before comparing.

like image 955
user1726273 Avatar asked Oct 12 '12 08:10

user1726273


1 Answers

From the MDN page on comparison operators:

For relational abstract comparisons (e.g. <=), the operands are first converted to primitives, then the same Type, before comparison.

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

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

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

This compares the two strings. Since "20a" is greater (alphabetically) than "10", it is true.

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

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

like image 154
lonesomeday Avatar answered Sep 29 '22 14:09

lonesomeday