- Published: Thursday, 12 September 2013 12:38
- Written by JPro Extensions
- Hits: 1801
When evaluating code, it is important to know exactly with which types of data we are working with and also to which type of software is it related, because sometimes, things aren't that logical as we might think and the results might not be the expected or desired.
// type of 0 is number // type of null is null 0 === null; // returns false 0 == null; // returns false 0 == +null; // returns true (type of null is now number) 0 === +null; // returns true (type of null is now number) 0 >= null; // returns true 0 <= null; // returns true
In the above comparisons, we can notice something - zero is not equal to null when performing the strict equality (===) or just the simple equality (==) operations. Then, when performing relational operations (>= or <=) we notice that the result of these evaluations always returns true, which means that, in plain words, zero is greater then or equal to null, and zero os less then or equal to null. Now, compare these results with the first evaluations where we concluded that zero is not equal to null.
On ECMAScript 5.2, in the Abstract Equality Comparison Algorithm, while performing the comparison x == y, there is no condition when Type(x) is 0 and Type(y) is null, thus, it skips to step 10 where the comparison returns false. Zero is then not equal to null.
PHP (on 5.3.1)
<?php // 0 is type integer // null is type NULL is_null(0); // returns false is_null(NULL); // returns true 0 == null; // returns true 0 == +null; // returns true 0 === null; // returns false 0 === +null; // returns true 0 >= null; // returns true 0 <= null; // returns true ?>
It's important not to take by granted the logical behaviors of each language, just because, at the first sight, we believe that the results should logically be the same. This is just one of the several cases where the final result is different from the expected.
"Zero is not equal to null. It is also not greater than null or less then null, but... zero is greater or equal than null and less than or equal to null."