0

I was playing around with comparing version codes in JS and found that these types of comparisons work consistently and I have no idea why:

"3.4.06" < "3.4.02"   (false)
"3.3.01" < "3.4.02"   (true)
"3.3.01" > "3.4.02"   (false)
"3.5.2"  < "3.4.1"    (false)
"3.5.2"  > "3.4.0015" (true)

These are obviously not valid numbers in javascript, but somehow the JS engine is comparing the string values in a way that makes things work. Can anybody give some insight into how the JS engine is doing this? I'm running on V8.

Evan Wieland
  • 1,445
  • 1
  • 20
  • 36
  • 1
    https://javascript.info/comparison Javascript compares strings letter by letter. And as you might know, a char is basically a number in memory. – Dimitri Bosteels Sep 12 '19 at 14:02
  • 1
    It just does lexicographical check character by character. `3` is before `4`, so `"3" < "4"` succeeds. However, that means that `"4" < "30"` is `false` since `4` comes after than `3` – VLAZ Sep 12 '19 at 14:03
  • lexical vs numerical. Stings are compared lexically. So `"100" < "9"`, because "1" comes before "9" and "100" isn't considered one whole entity. Numerical would compare the value of the entire number, where `100 > 9` – Shilly Sep 12 '19 at 14:04
  • Awesome! I had no idea about the lexical comparison. Thanks for the insight! – Evan Wieland Sep 12 '19 at 14:06

1 Answers1

1

Because JavaScript is comparing every char in order. Let's say "10" > "2", it will return false, because JS are comparing "1">"2" first then it will result in false

JPeter
  • 219
  • 1
  • 14