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
CunningFatalist
  • 453
  • 1
  • 9
  • 21

1 Answers1

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.

EasyPush
  • 756
  • 4
  • 13