You probably know ||
and &&
as OR and AND in conditions. They work by "short circuit evaluation", meaning ||
will stop evaluating and return the last expression as soon as any of the expressions (starting from the very left) evaluates to true
. (In other words: Since only one expression is required to be true for the whole compound to evaluate to true, we may stop as soon as any of them is true.) On the other hand &&
stops evaluating as soon as any of the expression is evaluating to false
(so the whole compound can't be true as soon as any of its parts is false). In other words, &&
will continue evaluating the terms as long as they are true
and ||
as long as the terms are false
.
Now, we may not only use these operators in conditions, but anywhere in the code. For example a && b();
is equivalent to the if-clause if (a) b();
. Similarly, ||
may be used for "is not": a || b();
is equivalent to if (!a) b();
.
Since ||
returns the value of the first term from the left that evaluates to true
, we may use this on the righthand-side in order to assign a default value (in case that the previous term(s) would evaluate to false
):
a = b || c;
is equivalent to
if (b) {
a = b;
}
else {
a = c;
}
We may do this with any number of terms:
var api = window.webAPI || window.webkitWebAPI || window.mozWebAPI;
(This would evaluate to the hypothetical "window.webAPI", or, if undefined, look for the "webkitWebAPI" and then for the "mozWebAPI".)
In the case of var x = x || {};
the construct just makes sure that x
is something (apparently something object-like), and if not, makes it an empty object ({}
).
It is equivalent to the if-clause
var x;
if (!x) x = {};
So, why would we use this? Obviously, when first encountered, it initializes variable x
to an empty object. But it does this conditionally: If x
would have been set before, it preserves the value of x
. Also, since we declare x
as a variable in the same clause, we make sure that we do not hit an undeclared identifier (saving an extra declaration on another line).