Conditional Operator

I learn best by doing, so when I’m trying to learn some new area, I usually build some demo for myself. Along the way, I often know what I want to do, but not HOW, so in my research, often look at other people’s code (this is particularly true for me as I don’t have a computer science background, so I will have the concept, but need some syntax).

So, periodically I’ll hit some piece of code that looks really new to me (even if it’s old hat to most). Awhile back I found one of these, and thought I’d mention how much I liked it: the conditional operator (also known as a ternary operator).

A typical if statement is something along these lines:

var ipad;
if(navigator.userAgent.match('iPad')){
ipad=true;
else{
ipad=false;
}

If the userAgent contains ‘iPad’, the ipad variable is true, otherwise false. So, there is 1) the condition to test, 2) what to do if it is one value, 3) and what to do if it is not…three pieces…ternary. So the alternate syntax for this is:

var ipad=navigator.userAgent.match('iPad')?true:false;

You’ve probably used this approach in an Excel IF statement, where you layout the condition to test, then the behavior if it succeeds, and if it fails. It’s not always helpful, maybe there isn’t an else, and so you’re just saving a couple of characters, or maybe if the condition is true, you have a lot of code…but it is a nice little tool to have in mind.

Another area where it can be helpful is when you have subtle differences, and only want to change a portion of content, and not duplicate the rest. For instance, on an iPhone, the safari tools are along the bottom, but in an iPad, they’re at the top. If I wanted to refer to it in my content (for instance, I have a web app that I want the user to install), I could have something like so:

if(ipad){
content='This page is designed as a web application, which means it can be installed to your iPad like any other application. Please press the arrow icon at the top of the screen, and then select Add to Home Screen.';
}
else{
content='This page is designed as a web application, which means it can be installed to your phone like any other application. Please press the arrow icon at the bottom of the screen, and then select Add to Home Screen.';
}

So I have the same content in my code twice, wasting space, and leaving me with multiple areas to edit if I want to make a change. Instead, I could have done the following:

content='This page is designed as a web application, which means it can be installed to your '+(ipad?'iPad':'phone')+' like any other application. Please press the arrow icon at the '+(ipad?'top':'bottom')+' of the screen, and then select Add to Home Screen.';

Isn’t that a bit better? This Wikipedia page has syntax examples for a number of languages.