Ternary Operator Precedence
You'll learn how the ternary operator fits into JavaScript's order of operations and when you need parentheses to make your intentions clear.
What is Operator Precedence?
Just like in math where 2 + 3 * 4 equals 14 (not 20) because multiplication happens before addition, JavaScript operators have a specific order. The ternary operator (? :) has very low precedence — it binds loosely, meaning most other operators run first.
How Ternaries Interact with Other Operators
Because ternaries have low precedence, they typically evaluate after arithmetic, comparison, and logical operators:
let x = 5 > 3 ? 10 : 20; // Comparison happens first → true ? 10 : 20 → 10
let y = 2 + 3 > 4 ? 'yes' : 'no'; // 5 > 4 → true ? 'yes' : 'no' → 'yes'
This usually works in your favor — you want the condition evaluated before the ternary decides which branch to take.
When Parentheses Matter
Problems arise when combining ternaries with assignment or other ternaries without clear grouping:
// Without parentheses — confusing!
let result = true ? 'a' : false ? 'b' : 'c'; // Evaluates left-to-right → 'a'
// With parentheses — crystal clear
let result = true ? 'a' : (false ? 'b' : 'c'); // Same result, but intention is obvious
If you're mixing ternaries with logical operators like && or ||, use parentheses to make the grouping explicit:
let score = true || false ? 10 : 5; // Unclear!
let score = (true || false) ? 10 : 5; // Clear: condition is (true || false)
Key Takeaway: The ternary operator has low precedence and binds loosely, so most operations happen before it evaluates — but always use parentheses when combining ternaries with other ternaries or complex expressions to keep your code readable.