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
The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.
Well, it's my understanding that || is going to be that Boolean "or," so this is going be "set current to either the variable called newGallery or zero," I believe!
The Logical OR operator ( || ) is an operator that returns its first or second operand depending on whether the first is truthy.
It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.
That Opera article gives a poor description of what is happening.
While it is true that x will get the value of 10 if v is undefined. It is also true that x will be 10 if v has any "falsey" value.
The "falsey" values in javascript are:
0nullundefinedNaN"" (empty string)falseSo you can see that there are many cases in which x will be set to 10 besides just undefined.
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/
var v = 0;  var x = v || 10;  alert( x ); // alerts 10   Assign v any of the falsey values that I indicated above, and you'll get the same result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With