Using the logical OR operator in setting variables

By David Pratt / Tags: / 2 Comments / Published: 11-01-10

If you ever find yourself setting a variable based on the existence of an object property or variable, and write tests similar to [Edit: assuming that the Object object is known to exist.]:

if ({
	var foo =;
	var foo = "foo";


var foo = "foo";
if ({
	foo =;

Then there is more elegant way to achieve this by using the logical OR (||) operator in setting the variable. The same result as above can be achieved by this line of code:

var foo = || "foo";

What this is in effect doing is testing the result of the logical OR operator based on the existence of the two conditions i.e. and “foo”. As “foo” will always resolve to true because it exists, it is just down to the ambiguity of to determine the output i.e. if exists, then foo will take the value of, otherwise it will adopt the value “foo”.

Category: Tech


Posted: on January 11th, 2010 at 11:58 am.

Feeds: RSS 2.0

2 Responses to “Using the logical OR operator in setting variables”

Miha January 11th, 2010 at 7:31 pm

It is not wise to test if ( since you don’t know if property was initialized yet. Testing property that has not been initialized is unpredictable.

Otherwise interesting “trick” :)

David Pratt January 11th, 2010 at 7:40 pm

Yep, that is indeed very true. I should have stated that the object is assumed to have been initialised.

Leave a reply