-2

Possible Duplicate:
Javascript Shorthand - What Does the '||' Operator Mean When Used in an Assignment?

var variable = obj1 || obj2;

Does it mean this?

var variable;

if (obj1)
{
    variable = obj1;
}
else if (obj2)
{
    variable = obj2:
}

Is it considered bad practise?

Community
  • 1
  • 1
Cheetah
  • 13,785
  • 31
  • 106
  • 190
  • 4
    possible duplicate of [Javascript Shorthand - What Does the '||' Operator Mean When Used in an Assignment?](http://stackoverflow.com/questions/4511301/javascript-shorthand-what-does-the-operator-mean-when-used-in-an-assignme) and [JavaScript || operator](http://stackoverflow.com/questions/1378619/javascript-operator). – Andy E Feb 23 '12 at 17:06

3 Answers3

5

The || operator returns its left hand side if resolves to be a true value, otherwise it returns its right hand side.

So it means the same as:

var variable;
if (obj1){
    variable = obj1;
} else {
    variable = obj2:
}

Note else, not, else if.

It is a common pattern and not usually considered bad practise.

The gotcha is that you need to be sure you want if (obj) and not if (typeof obj !== "undefined").

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Yup, that's what it means, and it's good practice

|| is a logical OR, so if obj1 = false you get false OR obj2 so the variable equals obj2

JKirchartz
  • 17,612
  • 7
  • 60
  • 88
0

How || expression works

The expression a || b value is determined by the last partial evaluated to determine Boolean truth.

false || 1 is evaluated as 1 is the last one evaluated.

true || 0 is evaluated as true as it is the last one evaluated.

How obj is evaluated in Boolean context

For an object in the context of Boolean value, object is evaluated to true unless null. It means even {} === true.

Combine the above two explanation, var variable = obj1 || obj2 assigns the first none null object from obj1 and obj2 to variable.

steveyang
  • 9,178
  • 8
  • 54
  • 80