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

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

    It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator".

    If you see any more funny symbols in JavaScript, you should try looking up JavaScript's operators first: Mozilla Developer Center's list of operators. The one exception you're likely to encounter is the $ symbol.

    To answer your question, conditional operators replace simple if statements. An example is best:

    var insurancePremium = age > 21 ? 100 : 200;
    

    Instead of:

    var insurancePremium;
    
    if (age > 21) {
        insurancePremium = 100;
    } else {
        insurancePremium = 200;
    }
    

提交回复
热议问题