Benefits of using the conditional ?: (ternary) operator

后端 未结 17 1309
孤街浪徒
孤街浪徒 2020-11-22 06:55

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

Conditional ?: Operator

17条回答
  •  庸人自扰
    2020-11-22 07:35

    I'd recommend limiting the use of the ternary(?:) operator to simple single line assignment if/else logic. Something resembling this pattern:

    if() {
         = ;
    }
    else {
         = ;
    }
    

    Could be easily converted to:

     =  ?  : ;
    

    I would avoid using the ternary operator in situations that require if/else if/else, nested if/else, or if/else branch logic that results in the evaluation of multiple lines. Applying the ternary operator in these situations would likely result in unreadable, confusing, and unmanageable code. Hope this helps.

提交回复
热议问题