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

前端 未结 18 1611
感动是毒
感动是毒 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:08

    The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

    condition ? expr1 : expr2 
    

    If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

    function fact(n) {
      if (n > 1) {
        return n * fact(n-1);
      } else {
        return 1;
      }
      // we can replace the above code in a single line of code as below
      //return (n != 1) ? n * fact(n - 1) : 1;
    }
    console.log(fact(5));
    

    For more clarification please read MDN document link

提交回复
热议问题