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

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

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

18条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 06:03

    Most of the answers are correct but I want to add little more. The ternary operator is right-associative, which means it can be chained in the following way if … else-if … else-if … else :

    function example() {
        return condition1 ? value1
             : condition2 ? value2
             : condition3 ? value3
             : value4;
    }
    

    Equivalent to:

    function example() {
        if (condition1) { return value1; }
        else if (condition2) { return value2; }
        else if (condition3) { return value3; }
        else { return value4; }
    }
    

    More details is here

提交回复
热议问题