For more tips like this, sign up to the weekly newsletter!

Know the precedence of the logical operators

Logical expressions usually take the form of either:

(...) &&
(... || ...) &&
(...)

or:

(...) ||
(... && ...) ||
(...)

As a best practice, you should always parenthesize the expressions, as this helps people instantly recognize the groupings.

But know that the && and the || have different precedence.

Precedence

From the precedence table, you can see that the && has the precedence of 6, while the || has 5.

This means that the && gets evaluated before the ||.

From the examples above, the latter does not require the parentheses:

... ||
... && ... ||
...

Knowing that there is an implicit grouping for the parts of ||s, it's easier to decipher some expressions:

true || true && false

is equal to:

(true) || (true && false)

Nevertheless, if you write the code, it's always better to make the intentions explicit and don't rely on the reader knowing the operator precedence.

But it's likely you'll see code without parentheses, and knowing at least a few operator's precedence helps understand these expressions better.

Try it
References
Learn more: