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

前端 未结 6 1499
梦毁少年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:21

    The OR function is a short-circuit OR evaluation - it returns the first element that is not false, or the last false element otherwise.

    This is actually quite useful, so you can write expressions like

    a = a || someValue;
    

    Which is the same as

    if (a==null)
      a = someValue;
    

提交回复
热议问题