17

I just took a look at this answer, and I noticed the following line of javascript code:

hrs = (hrs - 12) || 12;

My Question:

What does the '||' operator mean when used in an assignment?

Community
  • 1
  • 1
Jim G.
  • 15,141
  • 22
  • 103
  • 166

6 Answers6

12

In this case, the code assigns 12 to hrs if hrs-12 = 0 (as JavaScript sees it, 0 = false).

More generally, it assigns the latter value to the variable if the former value evaluates to 0, the empty string, null, undefined, etc.

nsdel
  • 2,233
  • 1
  • 16
  • 19
  • More specifically it would be if hrs12 <= 0. I mean, who knows how hrs is being set originally? – Casey Dec 22 '10 at 16:34
  • 2
    @Casey: not so, *ToBoolean* on negative numbers results in *true*, so really it will only assign 12 to `hrs` if `hrs-12 = 0` as the answer says. – Andy E Dec 22 '10 at 16:39
  • 1
    @Casey: It would only be `12` if `hrs - 12 == 0` (or some other falsey value). If it is less than `0`, it would be considered "true", and `hrs` would be assigned the negative value. – user113716 Dec 22 '10 at 16:39
7

It always means the same: logical OR

It's a common trick that makes use of type casting. Many non-boolean expressions evaluate to false. It's the same as this:

hrs = (hrs-12)
if(!hrs){
    hrs = 12;
}

And the if() works because 0 casts to false. It's also used to deal with undefined variables:

function foo(optionalValue){
    var data = optionalValue || "Default value";
}
foo();
foo("My value");
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
3

In the case of if hrs-12 evaluates to 0, the person wants hrs to be assigned 12 since 0 is not suitable.

Since 0 evaluates to false, the expression becomes false || 12, in which case 12 would be chosen since it's truthy.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
2

It means "If the first half of the expression is false, then use the second half instead."

Practically in this example, it means that hrs will be set to hours-12, unless hours-12 is zero, in which case it will hrs will be set to 12.

Spudley
  • 166,037
  • 39
  • 233
  • 307
1

It means "short circuit or". I.e. if the first part of the expression is false use the second instead. Wikipedia has an article on this with syntax for a number of languages.

Flexo
  • 87,323
  • 22
  • 191
  • 272
1

It means if hrs - 12 is evaluated to false (false, null, undefined, NaN, '', 0), then 12 will be assigned to hrs.

tszming
  • 2,084
  • 12
  • 15