Given this snippet of JavaScript...
var a;
var b = null;
var c = undefined;
var d = 4;
var e = \'five\';
var f = a || b || c || d || e;
alert(f); // 4
This is made to assign a default value, in this case the value of y
, if the x
variable is falsy.
The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.
The Logical OR operator (||
) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.
For example:
"foo" || "bar"; // returns "foo"
false || "bar"; // returns "bar"
Falsy values are those who coerce to false
when used in boolean context, and they are 0
, null
, undefined
, an empty string, NaN
and of course false
.