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

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

    I think you have basic JavaScript methodology question here.

    Now, JavaScript is a loosely typed language. As such, the way and manner in which it treats logical operations differs from that of other standard languages like Java and C++. JavaScript uses a concept known as "type coercion" to determine the value of a logical operation and always returns the value of the first true type. For instance, take a look at the code below:

    var x = mystuff || document;
    // after execution of the line above, x = document
    

    This is because mystuff is an a priori undefined entity which will always evaluate to false when tested and as such, JavaScript skips this and tests the next entity for a true value. Since the document object is known to JavaScript, it returns a true value and JavaScript returns this object.

    If you wanted a boolean value returned to you, you would have to pass your logical condition statement to a function like so:

    var condition1 = mystuff || document;
    
    function returnBool(cond){
      if(typeof(cond) != 'boolean'){ //the condition type will return 'object' in this case
         return new Boolean(cond).valueOf();
      }else{ return; }
    }    
    // Then we test...
    var condition2 = returnBool(condition1);
    window.console.log(typeof(condition2)); // outputs 'boolean' 
    

提交回复
热议问题