问题
Is there a specific reason why I have seen many people writing
if(1 === a) {...}
instead of
if(a === 1) {...}
I had given an answer in which I wrote something like Array === obj.constructor
which is when someone asked me that he has often seen people writing like this instead of obj.constructor === Array
.
So does it really matter which way I use?
回答1:
It's yoda conditions:
Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:
if ("red" === color) {
// ...
}
This is called a Yoda condition because it reads as, “red is the color”, similar to the way the Star Wars character Yoda speaks. Compare to the other way of arranging the operands:
if (color === "red") {
// ...
}
This typically reads, “color is red”, which is arguably a more natural way to describe the comparison.
Proponents of Yoda conditions highlight that it is impossible to mistakenly use = instead of == because you cannot assign to a literal value. Doing so will cause a syntax error and you will be informed of the mistake early on. This practice was therefore very common in early programming where tools were not yet available.
Opponents of Yoda conditions point out that tooling has made us better programmers because tools will catch the mistaken use of = instead of == (ESLint will catch this for you). Therefore, they argue, the utility of the pattern doesn’t outweigh the readability hit the code takes while using Yoda conditions.
来源:https://stackoverflow.com/questions/38035875/javascript-order-of-operands-in-comparison-operator