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
I agree with both Chris and J-P that:
var a = x ? 1 : 2;
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.