Operator precedence includes unary, increment, basic arithmetic, logical and assignment operators - roughly in that order.
The precedence can be remembered by BEUDMASLAS.
- brackets
- exponent
- unary & prefixed increment / decrement
- division
- multiplication
- addition
- subtraction
- logical
- assignment
- suffixed increment / decrement
Not quite exciting as BODMAS or PEDMAS (math, anyone?) and as it turns out - you would not even have to remember it :).
An outline with examples is below.
Type | Operator | Description | Example |
---|---|---|---|
Brackets | ( ) |
Two brackets to rule them all | 10 / (2+3) |
Exponential | ** |
2 ** 2 |
|
Unary & friends | + - ++ -- |
Unary operators, pre increment/decrement | ++i , -j |
Arithmetic | % * |
Binary arithmetic operations | i / j |
Arithmetic | + - |
Needs no explanation | i + j |
Logical | ! && || |
Logical operators in order of precedence | i && !j |
Assignment | += -= *= /= |
i += 1 |
|
Assignment | = |
Let there be assignment (at the end) | |
Post incr./decr. | ++ -- |
Changed value available to next operation | i++ |
Golden rule: put brackets whenever in doubt.
Priceless rule: Use prettier (and you should). It will automatically put brackets to clarify precedence and make the expression readable.
Let us look at some examples -
|
|