Why does JSHint dislike ternaries for method calls on objects?

后端 未结 3 540
一生所求
一生所求 2021-01-18 03:05

JSHint give the following error:

Expected an assignment or function call and instead saw an expression.

For the following line o

3条回答
  •  失恋的感觉
    2021-01-18 03:43

    There error is because a ternary is an expression. You could use it to set a variable:

    var result = a ? b : c;
    

    Notice that the ternary evaluates to either b or c. It's an expression.

    That said, the warning (I believe) comes from the notion that ternaries suffer poorer readability than an if...else block. The code above can be rewritten

    var result;
    if (a) {
        result = b;
    } else {
        result = c;
    }
    

    Which is easier to read than a ternary. JSHint does as much to promote readable code as it does valid code. If you're comfortable including these expressions in your code, go ahead and disable the warnings for expressions. (It's what I would do.)

提交回复
热议问题