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

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

    The JavaScript operator || is defined to return the left value if it evaluates to a truthy value, otherwise the right value instead of returning true itself. That's just how it's defined in the spec.

    I know it can be annoying at times, you might accidentally end up holding a reference to something you don't want to hold on to, but it also allows for the handy trick your example has. Everything has its pros and cons.

提交回复
热议问题