The Art of Nesting
Sometimes experienced developers chain several ternary operators together. This can look beautiful if code hygiene rules are followed.
1. When is this appropriate?
When you need to choose one of three or four values based on a simple check:
let access = (role === 'admin') ? 'Full' :
(role === 'user') ? 'Limited' :
'Guest';
2. Rules for Survival
- Vertical alignment: Write each
caseon a new line. - Simple conditions: Don't write complex formulas inside a ternary.
- Limit: If there are more than three branches — urgently switch to
if...elseor a lookup object.
Warning
If your code looks like a " ladder " of question marks that is impossible to read without a bottle of water — it means you've gone overboard with brevity.
Important
Always put parentheses around conditions. This helps to visually separate the logic from the result.