0

I was writing Javascript condition: "70.5" > "129" evaluate to true, while "70.5" > "729" evaluate to false. What does this mean? PS. In the end, I get the code working by parseFloat(70.5) > parseFloat(129). Want to know why I could not compare directly. Thanks.

mohammed wazeem
  • 1,310
  • 1
  • 10
  • 26
forrestg
  • 327
  • 5
  • 13
  • you are not using number literals, you are using string literals ... you don't need to `parseFloat(70.5)` since `70.5` is a Number ... as opposed to `"70.5"` which is a string ... so you'll see that `70.5 > 129` is false, and `70.5 > 729` is false – Bravo Nov 05 '19 at 04:13

1 Answers1

1

What is happening is that string literals are being compared with one another. While you are writing the number 70.5, JS sees this as a string with characters '7', '0', '.', '5'.

String literals are compared by their ASCII codes. So, a character that has a bigger ASCII code will be "larger" than the character that has a lower ASCII code.

Similarly,

var a = "a" > "b";
document.write(a); // Gives false

the above code snipped would print false, while

var a = "c" > "b";
document.write(a); // Gives true

would return true.

See this for more info.

Sanil Khurana
  • 1,129
  • 9
  • 20