In programming, readability is just as crucial as functionality. One area that often gets overlooked is the way we write comparisons. Using ambiguous comparisons can make your code harder to understand and lead to unexpected bugs. In this post, we'll look at how to make your comparisons in PHP and JavaScript both readable and reliable.
Readable PHP Comparisons
Beyond being a dynamic language, PHP has some weird and unexpected behavior when casting values. For instance, if you have a string with a zero, it will evaluate to false if you do !$string
.
So, in PHP, you are incentivized to do explicit comparisons not just for readability but also for correctness.
Check | Ambiguous form | Clear replacement |
---|---|---|
Is array empty? | !$list | $list === [] |
Is array empty? | empty($list) | $list === [] |
Is string empty? | !$string | $string === '' |
Is int zero? | !$int | $int === 0 |
Is null? | !$typeOrNull | $typeOrNull === null |
Scalar equals? | $a == $b | $a === $b |
Array key exists? | isset($list[$a]) | array_key_exists($a, $list) |
Is null or false? | !$mixed | $mixed === null || $mixed === false |
Readable JavaScript Comparisons
Check | Ambiguous form | Clear replacement |
---|---|---|
Is array empty? | !arr.length | arr.length === 0 |
Is string empty? | !str | str === '' |
Is number zero? | !num | num === 0 |
Is null? | !val | val === null |
Is equal? | a == b | a === b |
More Comparisons
What did I miss? Do you disagree with any of the above? Let me know in the comments!