Javascript:比较运算符中操作数的顺序

Javascript: Order of operands in comparison operator

有没有具体原因我看到很多人写

if(1 === a) {...}

而不是

if(a === 1) {...}

我已经给出了一个答案,其中我写了类似 Array === obj.constructor 的东西,这是当有人问我他经常看到人们这样写而不是 obj.constructor === Array 时。

那么我使用哪种方式真的很重要吗?

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.