3

Possible Duplicate:
What does this construct (x = x || y) mean?

a lot of times i can see that variables set like that

var d = d || {}

or

var = var || []

a few question came up to mind

  1. what it's mainly purpose ?
  2. how can it be to use OR in variable define?
Community
  • 1
  • 1
homerun
  • 19,837
  • 15
  • 45
  • 70

2 Answers2

3

If the left hand side is falsy (such as undefined, which a function argument is if it is not passed), it evaluates the right hand side. The last side to evaluate is returned in JavaScript, unlike some languages which return true or false. This is handy and why this construct is used.

It exploits short circuit evaluation.

The main reason it is used is to provide a sensible default if a parameter to a function is not passed.

var a = function(b) {
    b = b || [];
}

In the previous code example, if b was not passed, it is defaulted to a blank array ([]). However, if I passed 0 or something else falsy, it would become a blank array too. Be careful with this.

alex
  • 479,566
  • 201
  • 878
  • 984
  • @pst I made `Array` a code sample as it is a constructor for an array, and an actual type/object in the language. – alex Oct 18 '11 at 23:06
  • Yes, this construct is common and handy, but it can bite you when `0`, `false` and the empty string are legitimate values for the given context. – Matt Greer Oct 18 '11 at 23:08
  • @alex Wonder if it was SO's wonderful lack of optimistic concurrency again... I was just trying to format the larger code-block. –  Oct 18 '11 at 23:36
2

The || operator returns the left hand side if it is true and the right hand side if the left hand side isn't true.

So:

var d = d || {}

Is a quick way of saying:

var d;
if (!d) {
    d = {};
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • It should be noted that `var d = d || {}` will always assign a value to `d`, even it' the current value (although it's possible this could be optimized by a smart engine); in the case of `obj.x = obj.x || foo` this cannot be optimized in the face of custom getters/setters, but that's a different story ... somewhat. –  Oct 18 '11 at 23:06