3

Possible Duplicate:
What does “options = options || {}” mean in Javascript?

What does the following line of Javascript code do?

var somevar = window.somevar || {};
Community
  • 1
  • 1
VinnyD
  • 3,500
  • 9
  • 34
  • 48

3 Answers3

9

It sets somevar to window.somevar if window.somevar exists and is not boolean false, otherwise it sets it to an empty object {}

It's a common idiom for handling variables which may not have been set.

Rob Agar
  • 12,337
  • 5
  • 48
  • 63
0

It's an either/or assignment. If window.somevar is false or undefined, then somevar is set equal to {}. Otherwise it's set equal to window.somevar.

dgilland
  • 2,758
  • 1
  • 23
  • 17
0

This will evaluate the expression window.somevar as a boolean expression. If it evaluates to true then it will return the value of window.somevar. If it evaluates to false then it will return the empty object {}

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • Will it return the value of window.somevar or the reference? – Ketan Apr 01 '11 at 04:01
  • @Ketan actually I'm not sure. Going to find out ... – JaredPar Apr 01 '11 at 04:02
  • @Ketan experiments indicate it's set to the value. Though I'm not 100% sure on this point – JaredPar Apr 01 '11 at 04:03
  • My experiment suggests it's set to the reference. http://jsfiddle.net/ft8d2/2/ Edit:@dgilland is right – Ketan Apr 01 '11 at 04:06
  • 1
    It depends on what `window.somevar` is. If it's an object, then `somevar` will point to the same object that `window.somevar` points. So if you then modify a property of `window.somevar`, it will modify the corresponding property of `somevar`. – dgilland Apr 01 '11 at 04:06
  • 1
    @Ketan that's because in your scenario you created and modified an object. For simple values it uses the value (http://jsfiddle.net/RpvUp/). – JaredPar Apr 01 '11 at 04:07