Js Precedence in JavaScript
?? JavaScript Operator Precedence
Operator precedence determines the order in which operators are evaluated in expressions. Operators with higher precedence execute before those with lower precedence.
Why It Matters
For example:
let result = 3 + 4 * 5;Multiplication (
*) has higher precedence than addition (+), so4 * 5 = 20happens first, then3 + 20 = 23.If you want addition first, use parentheses:
(3 + 4) * 5 = 35.
Common Operator Precedence (High to Low)
| Precedence | Operators | Description |
|---|---|---|
| 20 | () | Parentheses (grouping) |
| 19 | ++, -- (postfix) | Postfix increment/decrement |
| 18 | ++, --, +, -, !, ~ | Unary operators |
| 17 | ** | Exponentiation |
| 16 | *, /, % | Multiplication, division, modulus |
| 15 | +, - | Addition, subtraction |
| 14 | <, <=, >, >= | Relational operators |
| 13 | ==, !=, ===, !== | Equality operators |
| 12 | && | Logical AND |
| 11 | ` | |
| 10 | ? : | Conditional (ternary) |
| 9 | =, +=, -=, *=, /=, etc. | Assignment |
| 8 | , | Comma operator |
Associativity
Most operators are left-to-right associative (evaluated from left to right).
Some, like exponentiation
**and assignment=, are right-to-left associative.
Example:
let x = 3 ** 2 ** 2; // Evaluated as 3 ** (2 ** 2) = 3 ** 4 = 81Example Expression with Explanation
let result = 5 + 10 * 2 / (3 - 1);Step-by-step:
(3 - 1)?210 * 2?2020 / 2?105 + 10?15
Final result = 15
Use Parentheses to Avoid Confusion
Always use parentheses () to clarify evaluation order and improve code readability.
If you'd like, I can provide a complete precedence table or help you understand a complex expression!