Associativity: Left-to-Right vs Right-to-Left
You'll learn: How JavaScript decides which operator to evaluate first when multiple operators have the same precedence level.
What Is Associativity?
You already know that precedence determines the order of operations (multiplication before addition, etc.). But what happens when operators have the same precedence? That's where associativity comes in.
Associativity is the rule that determines whether operators group from left-to-right or right-to-left when they share the same precedence level.
Left-to-Right Associativity
Most operators work left-to-right. When you chain them, JavaScript evaluates the leftmost operation first:
10 - 5 - 2 // Works like: (10 - 5) - 2 = 3
Since subtraction has left-to-right associativity, JavaScript groups from the left. The same applies to addition, multiplication, and division:
100 / 10 / 2 // Works like: (100 / 10) / 2 = 5
Right-to-Left Associativity
Some operators work right-to-left. The most common is the assignment operator:
a = b = c = 5 // Works like: a = (b = (c = 5))
This allows chaining assignments because assignment returns the assigned value. Exponentiation also works right-to-left:
2 ** 3 ** 2 // Works like: 2 ** (3 ** 2) = 2 ** 9 = 512
The Analogy
Think of a line at a café. Left-to-right is like serving customers in order (first come, first served). Right-to-left is like stacking dishes—you work from the top down (last placed, first handled).
Key Takeaway: Associativity determines grouping direction when operators have equal precedence—most operators group left-to-right, but assignment and exponentiation group right-to-left.