Truthy-ness (and falsy-ness)
An expression is "truthy" if it isn't "falsy". The "falsy" values are
- false (the boolean literal value)
- "" (the empty string)
- undefined
- null
- NaN (The special number value, representing not a number)
- 0 (that's the number, not the string)
The above values are evaluated as false, and all other values are true.
So, false (boolean literal false) is of course, false. But, perhaps unexpectedly "false" (string literal false), is considered truthy.
So you can say, "In Javascript 'false' is true". Absurd but true.
In your code you could right:
if ("false"===true) {
launchEntireGlobalNuclearArsenal();
}
And because of this interesting absurdity, such a snippet may just destroy the world.
Enough with the truthy-falsy, get on to the operators already!
So, again, <expression1> || <expression2> will return ....
the result of <expression1> if it evaluates to true, else, the result of <expression2>.
So, false || undefined evaluates to ... undefined.
undefined || "Hi!" evaluates to "Hi!"
You can use this to default the value returned from an expression.
someValue || 5.0 ... will evaluate to 5 if someValue is undefined. But if someValue is boolean false, it will also do that. As it will with other defined values. so maybe be careful. You would probably only intend for 5 to be defaulted if someValue===undefined.
Inverse to the behavior of the || operator is that of the && operator. && returns the first operand (left one) if it is falsy, else it returns the second.
Confused Yet?
If you are...well so was I. I would refer you to a lecture by Douglas Crockford, it will clarify and teach you some amazing things about javascript.
Finally:
Here is an example I setup on jsfiddle.net.