-5

I'm newbie and trying to study javascript myself.

There is an example:

 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop

I just wonder what does the symbol " ||" do? Thank you! Appreciate your help.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Quan Hoang
  • 45
  • 5
  • 6
    That's JavaScript's [logical OR operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators), which returns the value of the first operand if it is truthy, otherwise returns the value of the second operand. – nnnnnn Aug 30 '14 at 07:25
  • Also http://stackoverflow.com/questions/2851404/what-does-options-options-mean-in-javascript , http://stackoverflow.com/questions/7718259/what-does-mean (and *many* more, I just searched on SO for `[javascript] "||"`) – user2864740 Aug 30 '14 at 07:29

3 Answers3

7

It means that you are trying to get the document.documentElement.scrollTop function but if it returns undefined (because the function is not supported in the given browser) it will use the document.body.scrollTop function instead.

user2864740
  • 60,010
  • 15
  • 145
  • 220
Daniel Almeida
  • 400
  • 3
  • 8
  • 2
    If `document.documentElement.scrollTop` _is_ defined but happens to have the value `0` then the statement will take the value of `document.body.scrollTop`. – nnnnnn Aug 30 '14 at 07:33
0

If document.documentElement.scrollTop is undefined or null,scrollTop=document.body.scrollTop

yangsibai
  • 1,637
  • 12
  • 23
0

Here || Logical OR operator.

Logical OR operator returns the first value of first operand if that is truthy
otherwise it returns the second operand.

The above statement is same as

if(document.documentElement.scrollTop){
   var scrollTop = document.documentElement.scrollTop
}
else{
   var scrollTop = document.body.scrollTop
}
Mritunjay
  • 25,338
  • 7
  • 55
  • 68