Conditional Operators in Javascript

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

    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.

提交回复
热议问题