Taking Advantage of JavaScript's Flexible Ternary Operator

Let's face it, there are some parts of Javascript that simply aren't pretty to look at. At times I look at what my colleagues are doing in Ruby and it leaves me in complete envy. Yet there exists the potential to write beautiful Javascript if given proper attention.

One of the things I love in Ruby are the *.truthy? methods such as *.empty?. Let's try to create something similar in Javascript. First let's start off with a commonly implemented Javascript ternary:

var criminal = (suspects.length > 0) ? suspects[0] : "noone"

Nothing new, we've all seen this. But this is a little too heavy for my taste. What if we dropped the parentheses?

var criminal = suspects.length > 0 ? suspects[0] : "noone"

We're getting there. Now let's make things a little more concise:

var criminal = suspects.length ? suspects[0] : "noone"

Remember that if suspects is empty, suspects.length will return 0. Further, since we have not specified ===, the ternary will use type coercion in the conditional. Naturally, suspects.length registers as falsy because 0 gets coerced.

Let's take this a small step further by removing the whitespace after .length:

var criminal = suspects.length? suspects[0] : "noone";

Cool, I think the final example is significantly more straightforward and definitely less syntax heavy than where we started. It's actually is pretty similar Ruby:

# Ruby
criminal = suspects.length ? suspects[0] : "noone"
// Javascript
var criminal = suspects.length? suspects[0] : "noone";

Note that the space after .length in the first example is required because ? is a valid symbol in Ruby. I also find this to be particularly useful when creating classy functions where plain english style logic can be a nice addition:

1 function Cat(claws) {
2   this.claws = claws;
3 }
4 
5 var kitty = new cat();
6 
7 console.log( kitty.claws? "Ouch!" : "A-OK" );

No doubt, there are a handful of ways to write this. However I think the form deserves some more recognition. Further, understanding type coercion is important step in learning Javascript and this offers a great example of taking advantage of it to improve code readibility.