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

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

    I want to add some to the given answers.

    In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.


    Instead of:

    var welcomeMessage  = 'Hello ' + (username ? username : 'guest');
    

    You can use:

    var welcomeMessage  = 'Hello ' + (username || 'guest');
    

    This is Javascripts equivallent of PHP's shorthand ternary operator ?:

    Or even:

    var welcomeMessage  = 'Hello ' + (username || something || maybethis || 'guest');
    

    It evaluates the variable, and if it's false or unset, it goes on to the next.

提交回复
热议问题