Conditional Operators in Javascript

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

    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.

提交回复
热议问题