I really like aligning the ? and the : of my ternary operator when they don't fit on a line, like this:
var myVar = (condition
? ifTrue
: ifFalse
);
However, JSHint complains with:
Bad line breaking before '?'
Why would JSHint have this warning? Is there any nastyness (like semicolon insertion, etc) it is protecting me against or can I safely change my JSHINT configuration to ignore it?
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.
The conditional ternary operator can definitely be overused, and some find it quite unreadable. However, I find that it can be very clean in most situations that a boolean expression is expected, provided that its intent is clear.
This rule has a string option: "always" (default) enforces newlines between the operands of a ternary expression. "always-multiline" enforces newlines between the operands of a ternary expression if the expression spans multiple lines. "never" disallows newlines between the operands of a ternary expression.
continue is not an expression but a statement (which does not return anything). Other statements would give similar error in the ternary (such as declaring a variable with let). This is one reason to not rely excessively on the ternary to replace if/else logic.
This works and is certainly valid. It's especially useful in more complicated use cases, like nested ones.
var a = test1
? b
: test2
? c
: d;
UPDATE: This answer is outdated now. Apparently Crockford changes his mind ;)
See @CheapSteaks's answer for the update.
Per Crockford:
Place the break after an operator, ideally after a comma. A break after an operator decreases the likelihood that a copy-paste error will be masked by semicolon insertion.
So:
// this is ok
var myVar = (condition ?
ifTrue :
ifFalse
);
If you run this sample code through JSHint, this will pass:
// this is ok
var myVar = (1==1 ?
true :
false
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With