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?
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?
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.
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");
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.
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
.
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.
It means if hrs - 12 is evaluated to false (false, null, undefined, NaN, '', 0), then 12 will be assigned to hrs.