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

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

    This is a one-line shorthand for an if-else statement. It's called the conditional operator.1

    Here is an example of code that could be shortened with the conditional operator:

    var userType;
    if (userIsYoungerThan18) {
      userType = "Minor";
    } else {
      userType = "Adult";
    }
    
    if (userIsYoungerThan21) {
      serveDrink("Grape Juice");
    } else {
      serveDrink("Wine");
    }
    

    This can be shortened with the ?: like so:

    var userType = userIsYoungerThan18 ? "Minor" : "Adult";
    
    serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine");
    

    Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:

    userIsYoungerThan21 ? serveGrapeJuice() : serveWine();
    

    They can even be chained:

    serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine');
    

    Be careful, though, or you will end up with convoluted code like this:

    var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j;
    

    1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands]. It's the only one JavaScript currently has, though.

提交回复
热议问题