← All concepts
Fundamentals: Part 1

Operator Precedence and Associativity

When an expression mixes operators, precedence decides which one runs first, and associativity decides the order among operators of equal precedence.

Loading visual…

Definition

Every operator has a precedence level that determines how tightly it binds its operands. Multiplication and division bind tighter than addition and subtraction, so `2 + 3 * 4` evaluates the multiplication first (`3 * 4` → `12`) and then the addition (`2 + 12` → `14`), the same left-to-right-by-precedence rule taught in arithmetic. Comparison operators bind looser than arithmetic, logical `&&` binds tighter than `||`, and the assignment operators bind loosest of all, which is why `a = b + c` assigns the sum rather than trying to add `c` to the result of `a = b`. When two operators share the same precedence, associativity breaks the tie. Most binary operators, like `+` and `-`, are left-associative, evaluating left to right. A few, like the exponentiation operator `**` and the assignment operators, are right-associative, so `2 ** 3 ** 2` evaluates the rightmost `**` first (`3 ** 2` → `9`, then `2 ** 9` → `512`). Parentheses always override both rules, which is why wrapping a sub-expression in `()` is the clearest way to force a specific evaluation order.

Examples

2 + 3 * 4;   // 14, not 20: * runs before +
(2 + 3) * 4; // 20: parentheses override precedence

Multiplication has higher precedence than addition, so it evaluates first unless parentheses force a different order.

2 ** 3 ** 2; // 512, not 64: ** is right-associative
(2 ** 3) ** 2; // 64

Exponentiation groups from the right, so the rightmost ** evaluates first: 3 ** 2 is 9, then 2 ** 9 is 512.

true || false && false; // true, && binds tighter than ||
(true || false) && false; // false

&& has higher precedence than ||, so it is evaluated as true || (false && false), not (true || false) && false.

Where you see this

Practice this

Further reading