Javascript: Order of operands in comparison operator [duplicate]

落花浮王杯 提交于 2019-12-19 19:39:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!