Conditional Operators in Javascript

前端 未结 5 503
长发绾君心
长发绾君心 2021-02-07 06:22

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

5条回答
  •  渐次进展
    2021-02-07 06:40

    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.

提交回复
热议问题