Do we have a simpler ternary operator in JavaScript?

This question already has an answer here:

  • Is there a “null coalescing” operator in JavaScript? 8 answers

  • The Null coalescing operator is a recent addition to PHP. It was introduced in PHP 7 (released in December 2015), more than 10 years since the feature was proposed for the first time.

    In Javascript, the logical OR operator can be used for this purpose for ages (since Javascript was created?!).

    As the documentation explains:

    Logical OR ( || )

    expr1 || expr2

    Returns expr1 if it can be converted to true ; otherwise, returns expr2 .
    Thus, when used with Boolean values, || returns true if either operand is true ; if both are false , returns false .

    Instead of writing

    var name = obj['name'] ? obj['name'] : 'GOD';
    

    you can use the shorter:

    var name = obj['name'] || 'GOD';
    

    The || operator can be used several times to create a longer expression that evaluates to the value of the first operand that is not empty:

    var name = obj['name'] || obj['desc'] || 'GOD';
    

    In javascript you can do the following:

    var name = obj['name'] || "GOD"
    

    If the first value is false ( null , false , 0 , NaN , "" or undefined ), then the second value is going to be assigned.

    链接地址: http://www.djcxy.com/p/73366.html

    上一篇: Javascript一行If ... else ... else if语句

    下一篇: 我们在JavaScript中有一个更简单的三元运算符吗?