Javascript equality triple equals but what about greater than and less than?

后端 未结 4 2083
轮回少年
轮回少年 2021-02-07 05:11

I was explaining to a colleague that you should use === and !== (and >== and <== of course) when comparing variables in

4条回答
  •  Happy的楠姐
    2021-02-07 05:39

    12 > '100' // false
    '12' > 100 // false
    '12' > '100' // true
    

    As others mentioned, if one is a number the other is casted to a number. Same rule applies to these cases as well:

    null > 0 // false
    null < 0 // false
    null >= 0 // true
    

    However, there might be cases that you would need null >= 0 to give false (or any of the number string comparison cases above), therefore it is indeed a need to have strict comparison >== or <==.

    For example, I am writing a compareFunction for the Array.prototype.sort() and an expression like x>=0 would treat null values like 0's and put them together, whereas I want to put them elsewhere. I have to write extra logic for those cases.

    Javascript says deal with it on your own (in practice).

提交回复
热议问题