Decaffeinated: Double Brackets

2019-08-17 14:37发布

问题:

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