JavaScript || or operator with an undefined variable
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.
var x = v || 10;
That operator (the "logical" or "short-circuit" OR operator) would normally check the value of v
, and if it is a "falsy" value (i.e. it would fail as a condition used in an if statement), 10
becomes the value of x
, otherwise v
does (and if 10
were a function, it would never be executed).
undefined
, null
, and 0
are all examples of falsy values that a variable can hold (yes, even the first one), and the operator (or if statement) acts accordingly. In contrast, all objects and arrays (not including null) are "truthy" values, which allows for such things as this (used in the Google Analytics tracker code):
var _gaq = _gaq || []; // Makes a new array _gaq if it is not already there
However, if the referenced variable is not even declared anywhere within the scope chain, then a JavaScript exception will occur.
One way to avoid this is by declaring all your global variables from the start:
var iAmAGlobalVariable; // Holds the value undefined by default
If this is not possible, you should use the typeof
operator. It does not attempt to evaluate its operand, and thus an exception will not occur:
var x;
if(typeof v != 'undefined' && v) {
x = v;
} else {
x = 10;
}
Or even better, if you know that the variable would be a global variable, you can treat it as a property of the global (window) object:
var x = window.v || 10;
If v
evaluates to false (for example, 0
, null
, false
) then it won't work. You can manually check for undefined:
var x = v !== undefined ? v : 10;
I would use triple equals with ternary in a function for this.
function myTest(x){
return x === undefined ? true: false;
}
Only returns true if x is undefined
See (http://www.impressivewebs.com/why-use-triple-equals-javascipt/) and (http://jsfiddle.net/V76W6/)
I would just use a try-catch
var x = 0;
try
{
x = v;
}
catch(err)
{
x = 10;
}