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

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

    In the simplest terms:

    The || operator returns the first truthy value, and if none are truthy, it returns the last value (which is a falsy value).

    The && operator returns the first falsy value, and if none are falsy, it return the last value (which is a truthy value).

    It's really that simple. Experiment in your console to see for yourself.

    "" && "Dog"    // ""
    "Cat" && "Dog" // "Dog"
    "" || "Dog"    // "Dog"
    "Cat" || "Dog" // "Cat"

提交回复
热议问题