Yes you can go wild nesting ternaries. I find this version to be fairly readable:
var foo = (
bar === 'a' ? 1 : // if
bar === 'b' ? 2 : // else if
bar === 'c' ? 3 : // else if
null // else
);
but that's not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.
Yes you can go wild nesting ternaries. I find this version to be fairly readable:
var foo = (
bar === 'a' ? 1 : // if
bar === 'b' ? 2 : // else if
bar === 'c' ? 3 : // else if
null // else
);
but that's not a widely shared opinion, and you should probably stick to if/else or switch when working on a team.
Yes, you can use multiple condition in Ternary Operator. Hope this will help you.
var x=20;
var y = x<13 ? "Child" : x<20 ? "Teenage" : x<30 ? "Twenties" : "Old people";
console.log(y);
Multiple Conditional (Ternary) Operators
Nested ternary operators. How bad are they?
Can ternary operators contain multiple actions?
Javascript ternary operator syntax with object
Videos
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:
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 formatting2. 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!