0

I was wondering why the output of the following is all false.

12 > "goodbye"
12 < "goodbye"
10 > "2 beers"

I've looked all over the web and I haven't found anything that explains how to handle strings in comparison to numbers in javascript.

2
  • 1
    Shouldn't those strings have quotes around them? If so, can you edit your post to reflect this? Commented Jan 29, 2014 at 15:57
  • My bad, you're right, I forgot to add them. Commented Jan 29, 2014 at 16:12

1 Answer 1

1

When you try to compare strings to ints using equality operators, javascript will try to use the charCodes of the string's characters to compare to the number, which will naturally give some funky answers. You really shouldn't need to do comparisons with alphanumeric strings anyway, if you need to compare an int to a numeric string ("10" > 2) you can just use the parseInt() function: http://www.w3schools.com/jsref/jsref_parseint.asp

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your comment. I know I shouldn't, but this was an exam question of last year's exam, and since I need to give a correct answer, I was wondering how this actually works. But also, 10 > "2 beers" isn't done using parseInt automatically. Since if you do parseInt("2 beers") it will yield the integer 2, and 10 > 2 gives true. (Thus 10 > parseInt("2 beers") yields true). While 10 "2 beers" yields false. So what does it actually do?
It walks through the string and parses out the numeric characters, while ignoring letters. So with "2 beers", it works because the 2 is extracted and the rest of the string is ignored. If you start the string with a letter however (10 > parseInt("beers 2")), it will say the right side is NaN.
I already have the solution actually, someone in my class told me. It's really simple, you just can't compare strings and numbers like that, and that's why it's giving false. It doesn't have anything to do with the parseInt stuff. But thanks anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.