Do the && and || operators convert their operands to booleans?

前端 未结 4 1139
太阳男子
太阳男子 2020-12-09 11:13

Flanagan\'s O\'Reilly JavaScript book states:

Unlike the && and || operators, the ! operator converts its operand to a boolean value [...] b

4条回答
  •  孤街浪徒
    2020-12-09 11:51

    They do convert the values to boolean, but only to determine how to proceed in evaluating the expression. The result of the expression is not necessarily boolean (in fact, if neither of your operands are boolean, it will not give you a boolean):

    var x = false || 'Hello' // gives you 'Hello'
    var y = 0 && 1           // gives you 0, because 0 is "falsy" and short circuits
    var z = 1 || 2           // gives you 1, because 1 is "truthy" and short circuits
    

提交回复
热议问题