Decaffeinated: Double Brackets

对着背影说爱祢 提交于 2020-01-06 07:20:34

问题


I decaffeinated an old project recently and I noticed that I got a lot of if clauses where the expressions are wrapped in "extra" brackets:

if ((data == null) || (data === ""))

Is there any case where the wrapping is required? Imho it is the same as:

if (data == null || data === "")

回答1:


In that case it wouldn't matter, but whenever you remove parentheses from an if statement (or anywhere pretty much) make sure you check the precedence table.

For example, removing the parentheses from this:

if ((someVar && someConditional) == someBool)

Would result in:

if (someVar && someConditional == someBool)

Which is completely different. The first example, due to the parentheses, will evaluate someVar && someConditional first, then resultOfOperation == someBool. In the second example, due to the higher precedence of &&, someConditional == someBool is evaluated first, then 0 && resultOfOperation.




回答2:


With an explicit check, you could omit the parentheses around the comparisons, because of the lower operator precedence of ==/=== over logical OR ||.

if (data == null || data === "")


来源:https://stackoverflow.com/questions/56882749/decaffeinated-double-brackets

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