JavaScript Operator Precedence

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:

PrecedenceOperatorTypeExample
20()Grouping(2 + 3) * 4
17++, --Unary/postfixx++, --y
16!, +, -Unary!true, -x
15**Exponentiation2 ** 3
14*, /, %Multiplicative4 * 5, 10 / 2
13+, -Additive5 + 6, 8 - 2
12<<, >>Bitwise shiftx << 2
11<, >, <=, >=Comparisonx < y
10===, !==Equalitya === b
6&&Logical ANDa && b
5``
3=, +=, -=Assignmentx = 5, y += 1
2,Commaa = 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

  1. With parentheses:
jsCopyEditlet a = (3 + 2) * 4; // a = 5 * 4 = 20
  1. Without parentheses:
jsCopyEditlet b = 3 + 2 * 4;   // b = 3 + 8 = 11
  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *