The javascript ternary operator

Pop Quiz: Do you understand the Javascript ternary operator?

You said "yes" didn't you? Alright hotshot. See if you can analyze these statements correctly:

var x = 'steve_' + 10 == 10 ? 'A' : 'B';

If you answered 'steve_A', you'd be wrong.

How about:

var y = 'steve_' + (10 == 10) ? 'C' : 'D';

You think the answer is 'steve_C'? Wrong again.

How about:

var z = 'steve_' + (10 == 10 ? 'E' : 'F');

'steve_E'? Ok, that one was easy.

But what about the first two examples? Why aren't they yielding the obvious answer? Read on to find out.

The key is in understanding the order in which the Javascript interpreter analyzes the given examples.

Let's start with the first example:

var x = 'steve_' + 10 == 10 ? 'A' : 'B';

The Javascript interpreter is first going to evaluate the right side of this assignment statement: 'steve_' + 10 == 10 ? 'A' : 'B';.

Next, the Javascript interpreter will evaluate the left side of the ternary operator: 'steve_' + 10 == 10, from LEFT TO RIGHT.

The left to right here is critical. The Javascript interpreter will not first evaluate 10 == 10. This is the mistake most people make.

What the interpreter will do is concatentate 'steve' + 10. Then it will compare: 'steve_10' == 10.

And of course, 'steve_10' is not equal to 10, so at this point Javascript will determine that the variable x should be assigned the value 'B' and not 'A'.

You probably don't believe me, so go ahead and try it. Go ahead, I'll wait.

You see? The variable, x = 'B'.

The second example is even trickier in my opinion.

var y = 'steve_' + (10 == 10) ? 'C' : 'D';

Here again, the Javascript interpreter will first tackle the right side of the assignment statement. But in this example, we have parenthesis to consider. As one would expect, parenthesis mandate the highest order of precedence, so that's where Javascript is going to start with this example.

When Javcscript evaluates (10 == 10), the result is a boolean. Think about it. When Javascript encounters an if statement like: if (someVar == 10). The result of (someVar == 10) is either true or false. There are no other possibilities.

In our example, (10 == 10) evaluates to true. And since Javascript evaluates the left side of the ternary operator first, the next thing it will do is concatenate 'steve_' + true. Of course, true is not a string; it's a boolean value, but the Javascript interpreter will happily convert it to a string during concatenation.

So what we end up with on the left side of the ternary operator is: 'steve_true', which evaluates to true!

Wait, what? Yeah… I guess I can't just gloss over that one can I?

Yes, 'steve_true' absolutely resolves as true in an if conditional. Why? Because 'steve_true' is not null. And EMCAScript language specifications madate that null resolve to false in an if conditional (conversely, not null would resolve as true).

Since the evaluated left side of the ternary operator, 'steve_true', resolves as true, the variable, y will be assigned the value 'C'.

The last example is really the easiest one. If you were actually using code like this in your script, it's the syntax of the third example that you probably want.

var z = 'steve_' + (10 == 10 ? 'E' : 'F');

I don't think we need to spend a lot of time on this one, but here's the long and short of it.

Everything in parenthesis get evaluated first, so that's: 10 == 10 ? 'E' : 'F'.

Once again, the left side of the ternary operator will be evaluated first, and then the proper value will chosen from either 'E' or 'F'.

Since 10 == 10 is true, the value 'E' will be used in our expression. At this point, Javascript will concatenate 'steve_' and 'E', and the variable, z, will be assigned the value 'steve_E'.

So what have we learned from all of this? Hopefully we've learned not to make too many assumptions. Always test your code. Never assume you're so good as reading code that you know what the result will be. In Javascript especially, the little things can often wreak havoc.

Comments welcome.

6 thoughts on “The javascript ternary operator”

  1. I was staring at my JavaScript for ten minutes before turning to Google for some answers. Good insights here, thanks for the explanation!

  2. I spent roughly 2 hours reading websites on the ternary operator and none of them could explain my problem. I was about to give up when I found it here on your site – "…EMCAScript language specifications madate that null resolve to false in an if conditional (conversely, not null would resolve as true)."

    Thanks for all the help! BTW I got the first 2 examples wrong…thanks for explaining and helping me to understand it better.

  3. I've run into this kind of stuff so often that when I code now, I automatically enter "( () ? () : () )" on the line and then go back and fill in the interior parentheses. It's saved me tons of headaches.

  4. I got them right off the bat. Does that mean I'm almost a pro/exceptional student or does it just mean the large cookie I just ate kicked in straight away!

Leave a Reply

Your email address will not be published. Required fields are marked *