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

后端 未结 9 1905
耶瑟儿~
耶瑟儿~ 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:48

    You should think of the short-circuit operators as conditionals rather than logical operators.

    x || y roughly corresponds to:

    if ( x ) { return x; } else { return y; }  
    

    and x && y roughly corresponds to:

    if ( x ) { return y; } else { return x; }  
    

    Given this, the result is perfectly understandable.


    From MDN documentation:

    Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.

    And here's the table with the returned values of all logical operators.

提交回复
热议问题