Where to place operators in a multi-line ternary?
See original GitHub issueMy team uses airbnb’s styleguide as our default for coding style, although we do deviate occasionally.
Does airbnb have an opinion on where the operators should go in a multi-line ternary?
It’s not specifically talked about anywhere, but there is the example:
// better
const foo = maybe1 > maybe2
? 'bar'
: maybeNull;
one of our engs prefers this, with the justification that it’s easier to read. If you read the first line by itself, then having the ?
at the end lets you know that this is a ternary and is continuing. Otherwise, if you’re skimming the code very fast, you might think that you’re assigning foo
a boolean value.
const foo = maybe1 > maybe2 ?
'bar' :
maybeNull;
And again, we’re using multi-line ternaries because we have some long expressions and values to be assigned.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:7
- Comments:12
Top Results From Across the Web
multiline-ternary - ESLint - Pluggable JavaScript Linter
This rule enforces or disallows newlines between operands of a ternary expression. Note: The location of the operators is not enforced by this...
Read more >Can i use multiple line in ternary operator - Stack Overflow
The ternary conditional operator is an expression. It resolves to a value, which can be used elsewhere. For example: let x = someCondition...
Read more >Multiple lines in a ternary operator's clauses? - SitePoint
It's very important where you place parenthesis in nested ternary operators. Basically if you want a nest a ternary operator in an existing ......
Read more >Python Ternary Multiple Lines - Finxter
Ternary Operator : The most basic ternary operator x if c else y consists of three operands x , c , and y...
Read more >How to use the ternary operator in C++ - Educative.io
In C++, the ternary operator is used to replace a multiline if-else code with a single line. It's a shorthand if-else statement as...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Currently https://github.com/airbnb/javascript#comparison--nested-ternaries does permit multiline ternaries, although it discourages them. I’d strongly encourage you to use
let
andif
/else
rather than multiline ternaries.That said, the former is the only style I would expect to see one:
Can you elaborate on why you feel that to be the correct approach? Type safety is much easier when you disallow mutations and discourage nullable objects. Ternaries meet both criteria, whereas
let
often necessitates a host of additional checks.