Decaffeinated: Double Brackets

2019-08-17 14:31发布

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 === "")

2条回答
虎瘦雄心在
2楼-- · 2019-08-17 14:42

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-17 14:55

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 === "")
查看更多
登录 后发表回答