Why does Javascript's OR return a value other than true/false?

前端 未结 6 1488
梦毁少年i
梦毁少年i 2020-12-14 19:12

I saw this construction in order to get the browser viewport width:

function () { return window.innerWidth || document.documentElement.clientWidth || documen         


        
6条回答
  •  醉梦人生
    2020-12-14 19:31

    It's just the way it is by design. ||, like && is a short-circuit operator, the expressions are evaluated in order, they stop after an expression meets the criteria and yield the result of the expression. The same is true of &&:

    var  myObj  = { "Test": { "Foo":"Bar" } };
    var  myObj2 = { "Foo": "Bar" };
    
    alert(myObj.Test && myObj.Test.Foo); // will alert "Bar";
    alert(myObj2.Test && myObj2.Test.Foo); // will alert undefined;
    

提交回复
热议问题