Image of Aaron Gough, Software Developer

Ternary Quandry

When writing even fairly simple code in JavaScript you will encounter many situations where you need to test for the existence of a variable, and either use it or a secondary variable if it does not exist (or more correctly, does not evaluate to ‘true’). Consider this:

1 if( object.property )
2   {
3   var result = object.property;
4   }
5 else
6   {
7   var result = object.otherProperty;
8   }

This, while being easy to understand, clearly takes up a lot more room than it needs to. With this in mind many developers will turn to the Ternary operator to gain the same result in a more compact form:

1 var result = (object.property) ? object.property : object.otherProperty;

Personally I find the syntax of the Ternary operator confusing… Can you easily recall which variable is assigned when the condition is met? How about someone that has just started programming? What if it is used in the middle of another expression? I am a big believer in making the function of your code as obvious as possible and, for me at least, the Ternary operator does not contribute toward that ideal.

Enter the Or operator:

1 var result = object.property || object.otherProperty;

In this example we are using a lesser-known sprinkling of JavaScript’s syntactical sugar. If the object.property variable evaluates to true it is assigned, otherwise the Or operator jumps in and hands the second variable (object.otherProperty) to the receiving variable. To illustrate:

1 window.firstProperty = "Hello!";
2 window.secondProperty = "I'm number 2!";
3 
4 var result = window.firstProperty || window.secondProperty;
5 
6 alert( result ); // Hello!
1 // window.firstProperty === undefined;
2 window.secondProperty = "I'm number 2!";
3 
4 var result = window.firstProperty || window.secondProperty;
5 
6 alert( result ); // I'm number 2!

Often times this sort of structure is used to deal with the different APIs that the various web browsers expose to JavaScript. In this situation a great advantage of this method is that you can chain it as many times as needed, like this example taken from one of my projects:

1 var viewportHeight = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
2 //                    ^ FF, Safari, Opera             ^ IE6 Strict                  ^ All other explorers

This same technique is also usable in a few other languages, Ruby for one, and can greatly enhance the readability of your code while maintaining it’s brevity.