EMZETT.
Login

Operator Precedence

In short: The fixed order in which operators within an expression with several operators are evaluated — similar to the “multiplication before addition” rule from mathematics.

In more detail: Multiplication and division, for example, have higher priority than addition and subtraction, so 2 + 3 * 4 is evaluated as 2 + (3 * 4) = 14, not as (2 + 3) * 4. Parentheses explicitly override the default priority and also make complex expressions easier for humans to read — when in doubt, adding a parenthesis is worth more than relying on correctly remembering the precedence rules.

In Depth

An approximate, simplified ranking (high to low), as it holds in many C-like languages:

1. Parentheses ()
2. Unary operators (! - sign)
3. Multiplication, division, modulo (* / %)
4. Addition, subtraction (+ -)
5. Comparison operators (< > <= >= == !=)
6. Logical AND (&&)
7. Logical OR (||)
8. Assignment (=)

This order explains expressions that might seem ambiguous at first glance:

2 + 3 * 4 === 14        // multiplication before addition: first 3*4, then +2
a && b || c              // first a&&b (higher priority), then ||c
!isEmpty && size > 0  // first !isEmpty, then the comparison, then &&

Besides priority (WHICH operator goes first), associativity also plays a role for operators of equal priority — it determines in which direction evaluation happens when several equal-ranking operators appear in a row. Most arithmetic operators are left-associative (10 - 3 - 2 is read as (10 - 3) - 2 = 5, not as 10 - (3 - 2) = 9), while assignments are usually right-associative (a = b = 5 first assigns b = 5, then a = b).

In practice, it’s not a sign of weakness to generously add parentheses for more complex expressions, even when they aren’t technically necessary — code is read far more often than it’s written, and explicit parentheses spare anyone who later stumbles across the code (including yourself, months later) the tedious mental recalculation of the precedence rules.

See also: Operators, Arithmetic Operators