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

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

    In most programming languages, the && and || operators returns boolean. In JavaScript it's different.


    OR Operator:

    It returns the value of the first operand that validates as true (if any), otherwise it returns the value of the last operand (even if it validates as false).

    Example 1:

    var a = 0 || 1 || 2 || 3;
            ^    ^    ^    ^
            f    t    t    t
                 ^
                 first operand that validates as true
                 so, a = 1
    

    Example 2:

    var a = 0 || false || null || '';
            ^    ^        ^       ^
            f    f        f       f
                                  ^
                                  no operand validates as true,
                                  so, a = ''
    

    AND Operator:

    It returns the value of the last operand that validates as true (if all conditions validates as true), otherwise it returns the value of the first operand that validates as false.

    Example 1:

    var a = 1 && 2 && 3 && 4;
            ^    ^    ^    ^
            t    t    t    t
                           ^
                           last operand that validates as true
                           so, a = 4
    

    Example 2:

    var a = 2 && '' && 3 && null;
            ^    ^     ^    ^
            t    f     t    f
                 ^
                 entire condition is false, so return first operand that validates as false,
                 so, a = ''
    

    Conclusion:

    If you want JavaScript to act the same way how other programming languages work, use Boolean() function, like this:

    var a = Boolean(1 || 2 || 3);// a = true
    

提交回复
热议问题