Search code examples
javascriptstringnumberscomparison-operators

Confusion with comparision opertaor


Please help me understand how this works:

"1" > "01" returns true

BUT

1 > 01 returns false

Solution

  • comparison operator always compare value to respective place of operands, so here in the first example

      "1" > "01"
       |     ||
       |     ||________________  2nd ( 2nd operand )
       |     __________________  1st ( 2nd operand )
       _________________________ 1st ( 1st operand )
    

    so clearly 1 > 0 is true

    In second example value is number so leading 0 don't have any significance, so it is actually same as

    1 > 1 which is clearly false
    

    JS do not keep the leading zeros before any number

    let one = 00001
    console.log(one)
    console.log(000002)