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 -
let [x, y, z] = [1, 3, 5];
console.log(x / y + z); // 5.33
console.log(x + (x * y) / z ** 2); // 1.12
console.log(x + y * ++z); // 19
z--; //reset z to 5
console.log(x + y * z++); // 16. z is incremented after the entire operation
console.log(z); // 16
z = 5; //reset z to 5
console.log((z = x + y * z++)); // 16. z is incremented after the entire operation
console.log("reassigned:", z); // reassigned: 16
z = 5; //reset z to 5
console.log(i || (j && !k)); // true
console.log(1 + 5 / 2 && true); // true, since 3 = true
x = y += 1;
console.log(x, y); // 4 4
x = z *= 1 + 1;
console.log(x, z); // 10 10