return String vs Integer vs undefined vs null

后端 未结 6 1793
醉话见心
醉话见心 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 11:18

    Because this[x] is undefined, which is falsy, and so is null.

    The || operator returns the first "truthy" value it finds, and stops its evaluation at that point.

    If no "truthy" value is found, it returns the result of the last operand evaluated.

    There are a total of 6 "falsey" values. They are...

    1. false
    2. undefined
    3. null
    4. ""
    5. NaN
    6. 0

    Everything else is considered truthy.

    So your expression will be evaluated as...

    //   v--falsey            v--truthy! return it!
    ((((this[x] || null) || 'aïe') || 12) || undefined);
    //               ^--falsey         ^--------^---these are not evaluated at all
    

    Or you could look at it like this:

    (
      (
        (
          (this[x] || null) // return null
                /* (null */ || 'aïe') // return 'aïe' and stop evaluating
                                    || 12) 
                                          || undefined);
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题