0

today, I encountered something rather strange. Consider the following code (which I use to sync a range slider with an input element):

// val = "50"
// other_val = 100  
if( val > other_val ){
    console.log(val + '>' + other_val); // => 50 > 100
    console.log( val > other_val); // => true
    $input_max.val( other_val );
}

How did that happen? When I type

"50" > 100 

into my console (Chrome & FireFox), it says false, which is what I expected. I fixed the resulting bug with parseInt(), but I still don't know why this happened. Also, I don't know why I can't reproduce it outside of this script.

Any ideas? :)

Cheers!

Update:

As Bergi pointed out, it was "50">"100", and not "50" > 100. Thank you very much for that idea. Now, my real question seems to be:

Why does this return true:

"50">"100" // => true
9
  • You want to know why val + '>' + other_val resulted "50 > 100" ? Commented Mar 23, 2015 at 14:58
  • @DontVoteMeDown not what OP is asking.... Commented Mar 23, 2015 at 15:00
  • @DontVoteMeDown Looks like OP wants to know, why "50">100 logs true from a script, but false when you run it directly in the console. Commented Mar 23, 2015 at 15:00
  • 2
    Are you sure that it's not "100" instead of 100? Because "50" > "100". Commented Mar 23, 2015 at 15:01
  • 1
    So why is "50" > "100"? Edit: Oh, of course, it's a string compare sorting by character. And '5' > '1'. Commented Mar 23, 2015 at 15:03

1 Answer 1

1

The answer to your edited question is that when you compare strings it compares character by character from the beginning of the string. And the character 5 is "larger" than 1.

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

1 Comment

Tested it, "50">"100" returns true, "050">"100" returns false. Thanks, mate!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.