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.

Leave a Comment