I have been doing some reading lately one article I read was from Opera.
http://dev.opera.com/articles/view/javascript-best-practices/
In that article they write this:
Another common situation in JavaScript
is providing a preset value for a
variable if it is not defined, like
so:
if(v){
var x = v;
} else {
var x = 10;
}
The shortcut notation for this is the
double pipe character:
var x = v || 10;
For some reason, I can’t get this to work for me. Is it really possible to check to see if v is defined, if not x = 10?
–Thanks.
Bryan
That Opera article gives a poor description of what is happening.
While it is true that
xwill get the value of10ifvisundefined. It is also true thatxwill be10ifvhas any “falsey” value.The “falsey” values in javascript are:
0nullundefinedNaN""(empty string)falseSo you can see that there are many cases in which
xwill be set to10besides justundefined.Here’s some documentation detailing the logical operators. (This one is the “logical OR”.) It gives several examples of its usage for such an assignment.
Quick example: http://jsfiddle.net/V76W6/
Assign
vany of the falsey values that I indicated above, and you’ll get the same result.