0

I am learning Javascript and was reading about type coercion. Why it's giving me false on console.log('10' > '5')

console.log('10' > '5')
console.log('23' > '18')
  • 3
    There is no type coercion - you're comparing strings. "5" sorts *after* "10" the same way "dog" sorts *after* "apple" – VLAZ May 12 '21 at 13:24
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain. – Szabolcs Dézsi May 12 '21 at 13:25
  • 1
    Type coercion would come into play when comparing a string to a number, such as `'10' > 5` or `10 > '5'`, both of which yield `true`. – Ivar May 12 '21 at 13:26
  • @VLAZ when I execute this `console.log('I am ' + 32 + ' years old.')` Javascript converts `32` into string. I am still confused with this `console.log('23' > '18')` which returning `true`. – Muhammad Zeeshan May 12 '21 at 13:29
  • @MuhammadZeeshan the two pieces of code do two different things. So, yes, it's confusing to think they are the same. When you use `+` with a string and a number, the number is type coerced. If you use `>` with two strings, the strings are not coerced. – VLAZ May 12 '21 at 13:32
  • That makes sense @VLAZ. So for my understanding, can you please explain why `console.log('10' > '5')` is `false`. It would be helpful for me if you can share which operator can be used for coercion and which not. – Muhammad Zeeshan May 12 '21 at 13:36
  • 1
    @MuhammadZeeshan because these are *strings*. They are compared by their character's relation to each other. `"apple" > "dog"` also returns `false` because the letter "a" comes **before** the letter "d", not after it. The same way the character "1" comes **before** the character "5". not after it. It's alphabetic comparison, not numeric comparison, so it's comparing character by character. – VLAZ May 12 '21 at 13:46

0 Answers0