Quantcast
Channel: JavaScript – Xomino
Viewing all articles
Browse latest Browse all 34

Shorthand Conditional JavaScript variable checking using ||

$
0
0

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.



Viewing all articles
Browse latest Browse all 34

Trending Articles