Conditional Operators in Javascript

前端 未结 5 584
长发绾君心
长发绾君心 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:43

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

提交回复
热议问题