associativity and precedence in javascript

In JavaScript, operator precedence and associativity determine how expressions are evaluated when multiple operators are used together.


🔷 1. Operator Precedence (Priority)

Precedence defines which operator is executed first in an expression.

👉 Higher precedence = executed first
👉 Lower precedence = executed later

Example:

let result = 10 + 5 * 2;

👉 Here:

  • * has higher precedence than +
  • So calculation is:
5 * 2 = 10
10 + 10 = 20

✅ Output: 20


🔹 Common Precedence Order (High → Low)

OperatorDescription
()Parentheses
++ --Increment/Decrement
* / %Multiplication
+ -Addition/Subtraction
< > <= >=Comparison
== ===Equality
&&Logical AND
`
=Assignment

Example with Parentheses:

let result = (10 + 5) * 2;

👉 Parentheses override precedence:

10 + 5 = 15
15 * 2 = 30

✅ Output: 30


🔷 2. Associativity (Direction of Evaluation)

When operators have same precedence, associativity decides left-to-right or right-to-left evaluation.


🔹 Left-to-Right Associativity

Most operators follow this.

Example:

let result = 10 - 5 - 2;

👉 Evaluation:

10 - 5 = 5
5 - 2 = 3

✅ Output: 3


🔹 Right-to-Left Associativity

Assignment operators follow this.

Example:

let a, b, c;
a = b = c = 10;

👉 Evaluation:

c = 10
b = 10
a = 10

✅ Output:

a = 10, b = 10, c = 10

🔷 Combined Example

let result = 10 + 5 * 2 ** 2;

👉 Step-by-step:

  1. ** → 2² = 4
  2. * → 5 × 4 = 20
  3. + → 10 + 20 = 30

✅ Output: 30


🔷 Key Points to Remember

✔ Precedence = priority of operators
✔ Associativity = direction of execution
✔ Use () to control evaluation
✔ Always use parentheses for clarity in complex expressions


🔷 Simple Trick 💡

👉 BODMAS works here too:

Brackets → Orders (powers) → Division/Multiplication → Addition/Subtraction

🔷 JavaScript Associativity Table

OperatorDescriptionAssociativity
()GroupingLeft → Right
[]Array accessLeft → Right
.Object propertyLeft → Right
++ -- (postfix)Increment/DecrementLeft → Right
++ -- (prefix)Increment/DecrementRight → Left
! ~ + - typeofUnary operatorsRight → Left
**ExponentiationRight → Left ⚠️
* / %MultiplicationLeft → Right
+ -Addition/SubtractionLeft → Right
< <= > >=ComparisonLeft → Right
== != === !==EqualityLeft → Right
&&Logical ANDLeft → Right
``
??Nullish CoalescingLeft → Right
?:Ternary operatorRight → Left
=AssignmentRight → Left
+= -= *= /=Compound assignmentRight → Left
,Comma operatorLeft → Right

🔷 Important Cases (Must Know)

1️⃣ Exponentiation (Right → Left)

let result = 2 ** 3 ** 2;

👉 Evaluates as:

2 ** (3 ** 2) = 2 ** 9 = 512

2️⃣ Assignment (Right → Left)

let a, b, c;
a = b = c = 5;

👉 Works as:

c = 5 → b = 5 → a = 5

3️⃣ Ternary Operator

let result = true ? 1 : false ? 2 : 3;

👉 Evaluates Right → Left


🔷 Quick Memory Trick 💡

  • Most operators → Left to Right
  • Exceptions (Right to Left):
    • **
    • =
    • ?:
    • Unary operators (!, typeof, etc.)