1

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?

9

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! this explains why the result was always false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.