return String vs Integer vs undefined vs null

后端 未结 6 1750
醉话见心
醉话见心 2021-02-15 10:50

Why does javascript prefers to return a String over any other choices ?

Consider the following snippet.

var arr = [\'Hello1\', \'Hello2\', \         


        
6条回答
  •  攒了一身酷
    2021-02-15 10:57

    The code a || b is roughly equivalent to a ? a : b, or this slightly more verbose code:

    if (a) {
        result = a;
    } else {
        result = b;
    }
    

    Since || is left-associative the expression a || b || c is evaluated as (a || b) || c.


    So in simple terms this means that the || operator when chained returns the first operand that is "truthy", or else the last element.

    This feature can be useful for providing defaults when you have missing values:

    var result = f() || g() || defaultValue;
    

    You could read this as: Get the result of f(). If it's a falsey value, then try g(). If that also gives a falsey value, then use defaultValue.

提交回复
热议问题