Yesterday, while looking through some of my very first JavaScript programs I came across something that made me chuckle a little bit. Then today, I was reading a JavaScript article online and saw the same concept I used early on, still being used in what was a relatively recent article.
That’s when I realized that there are some beginner to intermediate JavaScript developers out there, who simply haven’t discovered JavaScript’s ternary operator and just haven’t really tried to dive deeper into the language. (By no means am I an advanced JS developer, but I guess I was one of the lucky ones who caught onto this rule early on.)
For those that aren’t familiar with ternary operator’s, it’s basically the use of logic to set the value of a variable based on a condition, in single statement. Currently, you may do something like this:
var x = 'foo',
y;
if (x === 'foo') {
y = 'bar';
} else {
y = 'foo';
}
This is quite verbose. Using a ternary operator provides a better, quicker and in my opinion, cleaner way of doing it:
var x = 'foo',
y = (x === 'foo') ? 'bar' : 'foo';
It may look confusing at first, but the format follows the following rules:
var foo = (condition) ? Value A : Value B;
The (condition) portion is exactly what you would have put in your if statement. You can think of the ? as saying “then” and the : represents the else of the conditional. What was once 7 lines of code, is now just 2.
Pretty straightforward, but very handy to know.
NOTE: The parentheses used above are simply to make things a bit more readable, however they are optional. The following examples are equivalent:
var foo = (condition) ? Value A : Value B;
var foo = condition ? Value A : Value B;

{ 2 comments… read them below or add one }
I realize this defeats the purpose of the blog explaining the ternary operator, but you may as well leave off the ternary operator since you are assigning the values true and false based on whether the expression (x==5) is true or false. Just set y = (x==5). Sorry I don’t know how to mark as code on this blog, but just wanted to point that out.
Nate-
You’re right on both accounts (yes it defeats the purpose and yes you can obviously use the (x==5) expression).
But, I have updated the post accordingly as to not confuse readers about a certain approach. The boolean has been removed.