views:

1535

answers:

5

Is it ok to use conditional operators like a statement like so?

(x == y) ? alert("yo!") : alert("meh!");

Or is it more correct to use it to assign a value like so?

z = (x == y) ? "yo!" : "meh!";

If it's not incorrect to use it like a statement, then is it possible to add more than one line of code for execution like so? Is it more correct to use ifthen and switch statements for multiple lines of code?

(x == y) ? (alert("yo!"), document.write("woot!")) : (alert("meh!"), document.write("blah!"));
+1  A: 

Either of the two methods are acceptable although you could have also written:

alert((x == y) ? "yo!" : "meh!");

Aside from that I would never recommend using an inline conditional for multiline statements, just use a standard if/else block. Given the syntax you entered isn't valid JS either, you could have placed the multiple statements into anonymous methods and yada yada, then you enter into a tangled mess of nearly unmanageable and unnecessarily difficult code. So again, standard if/else.

Quintin Robinson
thanks! i wasn't thinking of how to optimize it, but that's great. i still need to let it sink in that they can be used WITHIN expressions.
baokhangluu
+1  A: 

JavaScript won't prevent you from doing it, but it's very a unusual practice that will confuse anyone reading your code.

The conditional operator is almost always used for selecting two alternative values, not statements. An if statement is preferred for conditional branching of statements.

As to your last question, yes, if you really must, you can abuse the [] construct:

(x == y) ? [alert("yo!"), document.write("woot!")] : otherstuff();

But please don't. 8-)

RichieHindle
+3  A: 

It is entirely up to you, you can do it either way. You just have to ask yourself, tho, does this style follow company guidelines, and how readable do you want this code to be?

using if statements is way more readable.

personally, I only use the tertiary operator for simple and quick true/false conditions--where doing so makes sense--or where I need something "inline".

Muad'Dib
I think you mean "ternary (instead of "tertiary"), the adopted term for the "conditional operator" in JavaScript. It's only referred to as the ternary operator because it happens to be the only operator that accepts three operands in JavaScript.
J-P
yup, I meant ternary. it's Friday. :-)
Muad'Dib
+4  A: 

Conditional operators are intentionally succinct and especially useful for assignments:

var a = x ? 1 : 2;

Using them to conditionally run functions, while possible, should, for the sake of readability be done using IF/ELSE statements:

// This is possible but IMO not best practice:
X ? doSomething() : doSomethingElse();

While long-winded, most of the time, this is the better solution:

if (X) {
    doSomething();
} else {
    doSomethingElse();
}

One notable benefit to the IF/ELSE structure is that you can add additional tasks under each condition with minimal hassle.

Your last snippet is also possible but it looks somewhat long-winded and, again, might be better suited to a more conventional logical structure; like an IF/ELSE block.

That said, a conditional operator can still be readable, e.g.

(something && somethingElse > 2) ?
   doSomeLongFunctionName()
   : doSomeOtherLongFunctionName();

In the end, like many things, it's down to personal preference. Always remember that the code you're writing is not just for you; other developers might have to wade through it in the future; try and make it as readable as possible.

J-P
+1  A: 

I agree with both Chris and J-P that:

  1. Conditional operators are handy for short statements. J-P's variable assignment is a great example: var a = x ? 1 : 2;
  2. Multi-statement clauses should be separated on to separate lines, for readability.
  3. Conditional operators can be made readable as multiline statements with the right indentation, but if/else syntax is much more familiar to most developers. Readability is about matching the expectations of your reader, so familiarity is important.

I will add that multi-line conditional operators leave you open to semicolon insertion errors. Check out the JSLint documentation (see the section on "Line Breaking") for more on this. If you must use a multi-line conditional operator, make sure operators are at the end of each line. I would rework J-P's multi-line example thusly:

(something && somethingElse > 2) ?
   doSomeLongFunctionName() :
   doSomeOtherLongFunctionName();

As has been mentioned, there are many style guides out there and you can choose whichever you prefer. Some choices are more error-prone than others, however. Definitely take a close look at that JSLint documentation; it is a very well-thought-out style guide, and if you adhere to it, you can even use the JSLint tool to automatically check your code for potential problems.

Eric Nguyen