How should I understand these?
null>0 > false null==0 > false null>=0 > true
Comparisons convert null to a number, treating it as 0 . That's why (3) null >= 0 is true and (1) null > 0 is false. On the other hand, the equality check == for undefined and null is defined such that, without any conversions, they equal each other and don't equal anything else. That's why (2) null == 0 is false.
Use === if you want to compare couple of things in JavaScript, it's called strict equality, it means this will return true if only both type and value are the same, so there wouldn't be any unwanted type correction for you, if you using == , you basically don't care about the type and in many cases you could face ...
Example. In the following example, null is not greater than 0 and not equal to 0, but greater than or equal to 0. It looks very odd to hear. Because in mathematics if we have two numbers i.e a, b and if a is not less than the b then the possible scenarios are either a is greater than b or a is equal to b.
The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.
The relational operators (>=
and <=
), perform type coercion (ToPrimitive
), with a hint type of Number
, all the relational operators present have this behavior.
You can see the inner details of this process in the The Abstract Relational Comparison Algorithm.
On the other hand, the Equals operator (==
), if an operand is null
it only returns true
if the other is either null
or undefined
, no numeric type coercion is made.
null == undefined; // true null == null; // true
Check the inner details of this process in the The Abstract Relational Comparison Algorithm.
Recommended articles:
typeof
, ==
and ===
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With