JavaScript || or operator with an undefined variable
javascript
Solution
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:
- `0`
- `null`
- `undefined`
- `NaN`
- `""` (empty string)
- `false`
So 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.
Problem
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