Shorthand IF Statement

I reference this in my last post but didn’t really elaborate, so here goes. Shorthand IF statements (or Ternary operators) are great for simple comparisons based on variables or known value decisions, for example if you had the below flow in your code:

Basic ComparisonFlowchart

 

This is the basis for all code, on or off, yes or no, true or false, etc. The shorthand way always this comparison to be complete handled on one line and is infinitely useful. Okay enough flapping on, here is how it works:

comparison ? true process : false process;

// For Example
name == '' ? $('#name').addClass('formError').focus() : $('#name').addClass('formValid');

// The same code as a full IF THEN ELSE statement
if(name == ''){
 $('#name').addClass('formError').focus() ;
}else{
 $('#name').addClass('formValid');
}

This can be shortened even further if you simply need a boolean return of true or false for example: var isValid = data.ajaxResponse.isValid === 1;

Let the world know