Shorthand Conditional JavaScript variable checking using ||

In this article I will highlight a shorthand method of JavaScript conditional variable checking. The || operator is commonly recognized as “OR” but it’s usage is broader than some people would think.

You might have occasion to have a variable declaration purposefully override a desired value. In this example the start will be zero unless the start variable has been declared with and assigned value:

Long Hand

var start
/*..bunch o' code..*/
if (!start){
	start = 0
}

Shorter hand

var start
/*..bunch o' code..*/
start= (start) ? start : 0

Shortest Hand

var start
/*..bunch o' code..*/
var start= start || 0

This shorthand use of || can be used anywhere in your code for example, at the end of a function:

var start
/*..bunch o' code..*/
function doStuff(){
	//do some stuff
	return (start || 0) //return start or if that is null/blank/false then zero
}

As a point of reference you might see something like this at the start of an external library which uses Nested Namespacing of object declaration:

var utils = utils || {}

The reason it is done like this is to ensure that the global utils variable is either declared properly as a blank array, or if it already exists it is not over-written.

One thought on “Shorthand Conditional JavaScript variable checking using ||

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s