'The difference when using if statement true === something() vs something() === true [duplicate]
I've seen a lot of codes that places boolean in front, followed by comparison operator, and then the variable/function to test
if (true === something()) {
doStuff();
}
Instead of the usual
if (something() === true) {
doStuff();
}
Is there a real difference between them instead of personal preference?
Solution 1:[1]
The practice to put the value first for comparisons originates from a time when ==
was commonly used as a comparison operator (instead of ===
as today) and syntax highlighting and linting was not a standard. We just used simple text editors to write PHP at that time.
The "yoda style" syntax helped to avoid fatal typos in comparisons involving a variable:
$foo = false;
if ($foo = true) ...
silently results in true being assigned to variable $foo, which might not be the intention. (Also, the if is always true)
Whereas
$foo = false;
if (true = $foo) ...
results in a syntax error, saving you from a headache.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |