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 (object.property){
	var foo = object.property;
}else{
	var foo = "foo";
}

Or:

var foo = "foo";
if (object.property){
	foo = object.property;
}

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 = object.property || "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. object.property and “foo”. As “foo” will always resolve to true because it exists, it is just down to the ambiguity of object.property to determine the output i.e. if object.property exists, then foo will take the value of object.property, otherwise it will adopt the value “foo”.

Category: Tech

Tags:

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 (object.property) 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