Stop nesting ternaries in JavaScript
Stop nesting ternaries in JavaScript
Nesting ternary operators makes code more complex and less clear. Let's investigate other ways to write conditional expressions.
![Stop nesting ternaries in JavaScript](https://programming.dev/pictrs/image/54c3daa7-a30c-44e8-9c06-e9d7f322d96e.png?format=webp&thumbnail=256)
You're viewing a single thread.
Until JS supports switch expressions, nested ternaries will continue to be the most effective way to write multi-state conditionals.
Also, stop using linting tools that prioritize consistency over human readability, and then complaining that the code they generate is not easily-readable by humans.
10 0 Replyhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch - hasnt it had this forever? Or are you refering to something else?
5 0 ReplyPretty sure they meant
match
as in pattern matching, notswitch
as in switch/case/break.You can see the proposal here: https://github.com/tc39/proposal-pattern-matching
10 0 ReplyYour probably right, that looks quite desirable.
3 0 ReplyNah, I meant switch, as that's what it's called in C#-land. See above.
That proposal for matching looks interesting, but not quite the same, no.
1 0 ReplyAre you sure?
Your C# example:
var output = input switch { null => "Null", 0 => "Zero", > 0 => "Positive", _ => "Negative" };
JS proposal for match:
const output = match input { when null: "Null"; when 0: "Zero"; if input > 0: "Positive"; default: "Negative"; }
5 0 ReplyAha, yeah, I see it now. Looking forward to it.
1 0 Reply
Yeah, a switch expression is different than a switch statement. I'm not actually sure how many languages actually have them, but in C# its...
var output = input switch { null => "Null", 0 => "Zero", > 0 => "Positive", _ => "Negative" };
2 0 Reply