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

后端 未结 9 1910
耶瑟儿~
耶瑟儿~ 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条回答
  •  萌比男神i
    2020-11-22 06:51

    var _ = ((obj.fn && obj.fn() ) || obj._ || ( obj._ == {/* something */}))? true: false 
    

    will return boolean.

    UPDATE

    Note that this is based on my testing. I am not to be fully relied upon.

    It is an expression that does not assign true or false value. Rather it assigns the calculated value.

    Let's have a look at this expression.

    An example expression:

    var a = 1 || 2;
    // a = 1
    
    // it's because a will take the value (which is not null) from left
    var a = 0 || 2;
    // so for this a=2; //its because the closest is 2 (which is not null)
    
    var a = 0 || 2 || 1;    //here also a = 2;
    

    Your expression:

    var _ = (obj.fn && obj.fn() ) || obj._ || ( obj._ = {} );
    
    // _ = closest of the expression which is not null
    // in your case it must be (obj.fn && obj.fn())
    // so you are gettig this
    

    Another expression:

    var a = 1 && 2;
    // a = 2
    
    var a = 1 && 2 && 3;
    // a = 3 //for && operator it will take the fartest value
    // as long as every expression is true
    
    var a = 0 && 2 && 3;
    // a = 0
    

    Another expression:

    var _ = obj && obj._;
    
    // _ = obj._
    

提交回复
热议问题