Why don't logical operators (&& and ||) always return a boolean result?

后端 未结 9 1721
耶瑟儿~
耶瑟儿~ 2020-11-22 06:04

Why do these logical operators return an object and not a boolean?

var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );

var _ = obj &&          


        
9条回答
  •  花落未央
    2020-11-22 06:56

    We can refer to the spec(11.11) of JS here of:

    Semantics

    The production LogicalANDExpression :LogicalANDExpression &&BitwiseORExpression is evaluated as follows:

    1. Evaluate LogicalANDExpression.

    2.Call GetValue(Result(1)).

    3.Call ToBoolean(Result(2)).

    4.If Result(3) is false, return Result(2).

    5.Evaluate BitwiseORExpression.

    6.Call GetValue(Result(5)).

    7.Return Result(6).

    see here for the spec

提交回复
热议问题