Reputation: 6613
I just found a piece of code in which it is compared a string to an integer like this :
var result = "text" > 127;
and the result of this line of code is false. I have also tried to change it to equals or less than, and the result was still false:
var result = "text" === 127;
var result = "text" < 127;
What is the meaning to compare a string and a number like this if it always return false, or are there any cases when this will be true?
Upvotes: 1
Views: 107
Reputation: 6968
When you compare string with number the string is converted to number, but in this case, "text"
, the result is NaN
(translate is Not a Number). Always result false, because an NaN
is not a number to compare.
Verify with this:
var n1 = Number("text");
console.log(n1); //show NaN
So...
var result = "text" > 127;
Is equals
var result = NaN > 127; //result false always with any compare
But, if the text is a number can be converted
var result = "00999" > 127; //result true, because Number("00999") == 999
Upvotes: 1