-2

I can understand that JavaScript will convert the one data type to another data type to match the data types automatically. But I don't understand the following results. Please explain the same for better understanding.

console.log("32" > "4") //This result is showing false. when converting the number it must be true. But, why its showing as false?
console.log("32" < "4") //This result is showing true. Why?
console.log("32" > "14") // Its showing true. How?
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • The data types already match (two strings). There’s no conversion. – Ry- Nov 29 '20 at 03:21
  • 2
    Because 3 comes before 4 – chiliNUT Nov 29 '20 at 03:23
  • The values are not converted to numbers. If both are strings they are compared on character values. For JavaScript to interpret them as integer values at least one of the two needs to be an integer. `"32" > 4 //=> true`, `32 > "4" //=> true` – 3limin4t0r Nov 29 '20 at 04:01
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+how+does+string+comparison+work) of [How does string comparison work in JavaScript?](https://stackoverflow.com/q/38498110/4642212). – Sebastian Simon Nov 29 '20 at 11:05

1 Answers1

0

When javascript compares 2 strings, it compares the placement of the characters of the strings in a series, which for numbers is "0123456789".

The reason ("32" < "4" === true) is because 4 comes later than 3 in the series, that is, 4 is greater than 3 (JS always starts comparing with the first character). Javascript will only move on to the second character when the first character is equal in both strings. It performs the same operation and returns true, false or moves onto the next character. This is why:

"4" > "39" === true

"32" > "31" === true

"30" > "3" === true

And for your last example, I get the value of "32" < "14" as false.

Heisen
  • 153
  • 1
  • 4