In JavaScript, operator precedence determines the order in which operations are performed in an expression. When multiple operators are used in a single line of code, JavaScript uses a set of rules to decide which operation to perform first. Understanding operator precedence helps avoid logic errors and makes your code more predictable and readable.
🔢 What Is Operator Precedence?
Think of operator precedence like math. In the expression 2 + 3 * 4, multiplication is done before addition, so the result is 14, not 20. JavaScript follows similar rules when it comes to operators.
Each operator in JavaScript has a precedence level, which is a number that tells JavaScript which operation to do first. The higher the number, the higher the precedence.
📊 Operator Precedence Table (Common Operators)
Here are some commonly used operators in order of highest to lowest precedence:
| Precedence | Operator | Type | Example |
|---|---|---|---|
| 20 | () | Grouping | (2 + 3) * 4 |
| 17 | ++, -- | Unary/postfix | x++, --y |
| 16 | !, +, - | Unary | !true, -x |
| 15 | ** | Exponentiation | 2 ** 3 |
| 14 | *, /, % | Multiplicative | 4 * 5, 10 / 2 |
| 13 | +, - | Additive | 5 + 6, 8 - 2 |
| 12 | <<, >> | Bitwise shift | x << 2 |
| 11 | <, >, <=, >= | Comparison | x < y |
| 10 | ===, !== | Equality | a === b |
| 6 | && | Logical AND | a && b |
| 5 | ` | ` | |
| 3 | =, +=, -= | Assignment | x = 5, y += 1 |
| 2 | , | Comma | a = 1, b = 2 |
🧠 Associativity
When two operators have the same precedence, JavaScript uses associativity to decide which one to evaluate first.
- Left-to-right: Most operators (like
+,-,*) evaluate from left to right. - Right-to-left: Some operators like assignment (
=) or exponentiation (**) go right to left.
Example:
jsCopyEditlet result = 2 ** 3 ** 2; // 2 ** (3 ** 2) = 2 ** 9 = 512
🛠️ Examples in Action
- With parentheses:
jsCopyEditlet a = (3 + 2) * 4; // a = 5 * 4 = 20
- Without parentheses:
jsCopyEditlet b = 3 + 2 * 4; // b = 3 + 8 = 11
- Mixed operations:
jsCopyEditlet c = 10 - 3 + 2; // c = (10 - 3) + 2 = 9
✅ Best Practices
- Use parentheses to make your code more readable and control the order of operations clearly.
- Don’t rely on memorizing the whole precedence table — understand the basics and use parentheses when in doubt.
- Test expressions in the console to confirm how they’re evaluated.
🧾 Final Thoughts
Operator precedence is a crucial concept that ensures your JavaScript expressions behave as expected. With a solid understanding of the rules and the habit of using parentheses wisely, you’ll write cleaner and bug-free code.