Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, is it OK to put the ternary operator's `?` on then next line?

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?

like image 784
hugomg Avatar asked Aug 31 '11 15:08

hugomg


People also ask

What is the correct way to write a ternary operator in JavaScript?

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.

Are ternary operators bad practice?

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.

How do you write multiple lines in a ternary operator?

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.

Can we use continue in ternary operator JavaScript?

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.


2 Answers

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;
like image 110
pimvdb Avatar answered Oct 17 '22 14:10

pimvdb


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
);

like image 27
Mrchief Avatar answered Oct 17 '22 13:10

Mrchief