How do you use the ? : (conditional) operator in JavaScript?

前端 未结 18 1604
感动是毒
感动是毒 2020-11-21 05:48

In simple words, what is the ?: (conditional, "ternary") operator and how can I use it?

18条回答
  •  梦如初夏
    2020-11-21 05:55

    Ternary expressions are very useful in JS, especially React. Here's a simplified answer to the many good, detailed ones provided.

    condition ? expressionIfTrue : expressionIfFalse
    

    Think of expressionIfTrue as the OG if statement rendering true;
    think of expressionIfFalse as the else statement.

    Example:

    var x = 1;
    (x == 1) ? y=x : y=z;
    

    this checked the value of x, the first y=(value) returned if true, the second return after the colon : returned y=(value) if false.

提交回复
热议问题