Sharing, Collaborating and Learning.

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: