Your alternatives here are basically:

  1. That if/else you don't want to do
  2. A switch combined with if/else

I tried to come up with a reasonable lookup map option, but it got unreasonable fairly quickly.

I'd go for #1, it's not that big:

if (res.distance == 0) {
    word = 'a';
} else if (res.distance == 1 && res.difference > 3) {
    word = 'b';
} else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) {
    word = 'c';
} else {
    word = 'd';
}

If all the braces and vertical size bother you, without them it's almost as concise as the conditional operator version:

if (res.distance == 0) word = 'a';
else if (res.distance == 1 && res.difference > 3) word = 'b';
else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) word = 'c';
else word = 'd';

(I'm not advocating that, I never advocate leaving off braces or putting the statement following an if on the same line, but others have different style perspectives.)

#2 is, to my mind, more clunky but that's probably more a style comment than anything else:

word = 'd';
switch (res.distance) {
    case 0:
        word = 'a';
        break;
    case 1:
        if (res.difference > 3) {
            word = 'b';
        }
        break;
    case 2:
        if (res.difference > 5 && String(res.key).length > 5) {
            word = 'c';
        }
        break;
}

And finally, and I am not advocating this, you can take advantage of the fact that JavaScript's switch is unusual in the B-syntax language family: The case statements can be expressions, and are matched against the switch value in source code order:

switch (true) {
    case res.distance == 0:
        word = 'a';
        break;
    case res.distance == 1 && res.difference > 3:
        word = 'b';
        break;
    case res.distance == 2 && res.difference > 5 && String(res.key).length > 5:
        word = 'c';
        break;
    default:
        word = 'd';
        break;
}

How ugly is that? :-)

Answer from T.J. Crowder on Stack Overflow
Top answer
1 of 16
44

Your alternatives here are basically:

  1. That if/else you don't want to do
  2. A switch combined with if/else

I tried to come up with a reasonable lookup map option, but it got unreasonable fairly quickly.

I'd go for #1, it's not that big:

if (res.distance == 0) {
    word = 'a';
} else if (res.distance == 1 && res.difference > 3) {
    word = 'b';
} else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) {
    word = 'c';
} else {
    word = 'd';
}

If all the braces and vertical size bother you, without them it's almost as concise as the conditional operator version:

if (res.distance == 0) word = 'a';
else if (res.distance == 1 && res.difference > 3) word = 'b';
else if (res.distance == 2 && res.difference > 5 && String(res.key).length > 5) word = 'c';
else word = 'd';

(I'm not advocating that, I never advocate leaving off braces or putting the statement following an if on the same line, but others have different style perspectives.)

#2 is, to my mind, more clunky but that's probably more a style comment than anything else:

word = 'd';
switch (res.distance) {
    case 0:
        word = 'a';
        break;
    case 1:
        if (res.difference > 3) {
            word = 'b';
        }
        break;
    case 2:
        if (res.difference > 5 && String(res.key).length > 5) {
            word = 'c';
        }
        break;
}

And finally, and I am not advocating this, you can take advantage of the fact that JavaScript's switch is unusual in the B-syntax language family: The case statements can be expressions, and are matched against the switch value in source code order:

switch (true) {
    case res.distance == 0:
        word = 'a';
        break;
    case res.distance == 1 && res.difference > 3:
        word = 'b';
        break;
    case res.distance == 2 && res.difference > 5 && String(res.key).length > 5:
        word = 'c';
        break;
    default:
        word = 'd';
        break;
}

How ugly is that? :-)

2 of 16
40

To my taste, a carefully structured nested ternary beats all those messy ifs and switches:

const isFoo = res.distance === 0;
const isBar = res.distance === 1 && res.difference > 3;
const isBaz = res.distance === 2 && res.difference > 5 && String(res.key).length > 5;

const word =
  isFoo ? 'a' :
  isBar ? 'b' :
  isBaz ? 'c' :
          'd' ;
🌐
Sonar
sonarsource.com › blog › stop-nesting-ternaries-javascript
Stop nesting ternaries in JavaScript | Sonar
December 7, 2023 - This has come after years of disagreement over the best and most readable way to format a nested ternary. I have a better idea of how to make nested ternaries clearer: stop nesting them. The ternary operator is an alternative ...
🌐
The New Stack
thenewstack.io › home › the trouble with nesting ternaries in javascript
The Trouble with Nesting Ternaries in JavaScript - The New Stack
February 1, 2024 - The ternary conditional operator is an alternative to if/else statements that make decisions based on a condition. Because the conditional operator is an expression that returns its result, it is tempting to nest further expressions within the ...
🌐
Medium
medium.com › javascript-scene › nested-ternaries-are-great-361bddd0f340
Nested Ternaries are Great. Note: This is part of the “Composing… | by Eric Elliott | JavaScript Scene | Medium
February 28, 2018 - In functional programming, we tend to avoid mutations and other side-effects. Since if in JavaScript naturally affords mutation and side effects, many functional programmers reach for ternaries instead — nested or not.
🌐
Accreditly
accreditly.io › articles › dont-nest-ternary-operators-please
Don't nest ternary operators. Please! - Accreditly
December 23, 2025 - While ternary operators are a useful ... Opting for clearer, more straightforward alternatives like if-else statements, switch statements, or function abstraction makes your code more accessible and maintainable....
🌐
ESLint
eslint.org › docs › latest › rules › no-nested-ternary
no-nested-ternary - ESLint - Pluggable JavaScript Linter
/*eslint no-nested-ternary: "error"*/ const thing = foo ? bar : baz === qux ? quxx : foobar; foo ? baz === qux ?
Find elsewhere
🌐
DEV Community
dev.to › samholmes › an-alternative-to-ternary-5cei
An Alternative Ternary - DEV Community
May 27, 2019 - Parentheses are important. The rule is to always wrap your outcome expression: condition && (outcome) || (outcome). Doing so will allow you to nest more conditional expression within the outcome expressions clearly.
🌐
Reddit
reddit.com › r/react › nested ternary operators. how bad are they?
r/react on Reddit: Nested ternary operators. How bad are they?
January 26, 2024 -

So I saw an article recently that was talking about minimizing the use of ternary operators where possible and reflecting on my own use of them especially in JSX, I have a few questions...

Before I get decided to post my questions, I checked React subs and most discussions on this are a couple years old at least and I thought perhaps views have changed.

Questions:

  1. Is the main issue with using nested ternary operators readability?

I have found myself using ternary operators more and more lately and I even have my own way of formatting them to make them more readable. For example,

            info.type === "playlist"
            ?   info.creationDate
                ?   <div className="lt-info-stats">
                        <span className="text pure">Created on {info.creationDate}</span>
                    </div>
                :   null
            :   info.type === "artist"
                ?   <div className="lt-info-stats">
                        <span className="text pure">{info.genre}</span>
                    </div>
                :   <div className="lt-info-stats">
                        <span className="text pure">{info.releaseDate}</span>
                        <span className="cdot" style={{ fontWeight: "bold", margin: "1px" }}>·</span>
                        <span className="text pure">{info.genre}</span>
                    </div>

When written like this, I can visually see the blocks and tell them apart and it looks a lot like how an if/else might look.

nested ternary operator formatting

2. What is the preferred formatting of ternary operators in general and what do you think should be done to make them more readable?

3. How do people feel about nested ternary operators today? How big of a nono is it to have them in code (if it is a nono)?

I would love you know peoples thoughts on ternary operators in React in general as well.

Thanks for your attention!

🌐
EyeHunts
tutorial.eyehunts.com › home › nested ternary operator javascript | example code
Nested ternary operator JavaScript | Example code
November 22, 2022 - You can nest one ternary operator as an expression inside another ternary operator to work as a Nested ternary operator in JavaScript.
🌐
Coding Beauty
codingbeautydev.com › home › posts › how to use the javascript nested ternary operator
How to Use the JavaScript Nested Ternary Operator - Coding Beauty
November 30, 2022 - We can use this to replace if…else if…else statements and switch statements. For example, we could have a piece of code that sets the English word for the numbers 1, 2, and 3 to a variable.
🌐
codestudy
codestudy.net › blog › alternative-to-nested-ternary-operator-in-js
Alternative to Nested Ternary Operators in JavaScript: Better Solutions Without If/Else Statements — codestudy.net
In this blog, we’ll explore clean, maintainable alternatives to nested ternary operators that avoid the pitfalls of both nested ternaries and traditional if/else statements.
🌐
SonarSource
rules.sonarsource.com › javascript › rspec-3358
Ternary operators should not be nested
Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your JAVASCRIPT code
🌐
Reddit
reddit.com › r/reactjs › what's the ternary operator alternatives?
What's the ternary operator alternatives? : r/reactjs
July 29, 2021 - The point of a ternary is to make ... Nested ternaries is an absolutely brutal, wanton and avoidable abuse of the syntax. ... In general either a lookup table, switch statement or if/else is all ok. For this specific instance, though, why is this even done in JavaScript...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Conditional_operator
Conditional (ternary) operator - JavaScript | MDN
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if...else statement.
🌐
Plain English
plainenglish.io › home › blog › javascript › how to use the javascript nested ternary operator
How to Use the JavaScript Nested Ternary Operator
May 17, 2022 - We can use this to replace if…else if…else statements and switch statements. For example, we could have a piece of code that sets the English word for the numbers 1, 2, and 3 to a variable.
🌐
DEV Community
dev.to › accreditly › dont-nest-ternary-operators-please-1g08
Don't nest ternary operators. Please! - DEV Community
January 25, 2024 - While ternary operators are a useful ... Opting for clearer, more straightforward alternatives like if-else statements, switch statements, or function abstraction makes your code more accessible and maintainable....
🌐
Scaler
scaler.com › home › topics › javascript › javascript ternary operator
JavaScript Ternary Operator - Scaler Topics
February 19, 2024 - JavaScript's Ternary Operator (?:) condenses conditional logic with three operands, offering an alternative to if-else statements. Enhancing code readability and simplicity, it enables concise representation of conditional blocks within expressions.