TOC

The community is working on translating this tutorial into Italian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Operators:

Conditional (ternary) operator

In a previous article, we spent a bit of time writing if-statements, a very powerful control structure found in pretty much any programming language, allowing you to control the flow of your code based on one or several conditions.

We also wrote code using the if..else construct, where we define two actions but only take one of them, based on the condition. Here's one of the examples we used:

var answer = confirm("Is it true?");
if(answer == true)
	alert("I knew it was true!");
else
	alert("Oh well, guess not then...");

It's quite easy to read and understand, but also a bit verbose. Fortunately for us, JavaScript, just like many other programming languages, comes with a shorter notation for the if..else statement, in the form of the conditional operator, sometimes referred to as the ternary operator. It looks like this:

condition ? actionIfTrue() : actionIfFalse();

So just like the if..else statement, there are three parts: A condition, an action to take if the condition is true and an action to take if the action is not true. This allows us to take all the 5 lines of code from the first example and turn it into a single, albeit a bit long, line of code:

confirm("Is it true?") ? alert("I knew it was true!") : alert("Oh well, guess not then...");

You may or may not like this short version of the if..else statement. Some people find it harder to read, while other people likes how it keeps their code short and concise.

Handling NULL's

A situation where this operator is very commonly used is when you need to check a value for NULL before using it, with the ability to supply a fallback value. This is especially useful in JavaScript where you can specify a variable as the condition, because it will evaluate to false if the variable is NULL. This also allows us to do the check directly within another statement, for instance like we do in this example:

let name1 = "John Doe", name2 = null;
alert("Hello, " + (name1 ? name1 : "unknown person") + "!");
alert("Hello, " + (name2 ? name2 : "unknown person") + "!");

Notice how I use the name1 and name2 variables as both the condition as well as the "action" if the condition evaluates to true. As the third part of the statement, I supply a fallback value. This works because the conditional operator will actually return the result of which ever action it takes, so in this case, either the name or the string "unknown person" will be returned and then immediately used by the alert() function.

To illustrate that, we could make the example a bit more verbose and store the outcome of the conditional operation in a variable before using it:

let name1 = null;
let personToGreet = (name1 ? name1 : "unknown person");
alert("Hello, " + personToGreet + "!");

Conditional operator chaining

As you can see, the conditional operator is quite flexible, but it doesn't have to stop there. You can turn of the actions into a conditional operation, as many times as you want, basically creating a series of if..else statements in one line. In the article on if-statements, I demonstrated how to chain multiple if..else statements together, like this:

var age = prompt("What's your age?");
if(age < 1)
	alert("Infant");
else if(age < 13)
		alert("Child");
	else if(age < 18)
		alert("Teenager");
	else
		alert("Adult");

But you can actually rewrite this as a single line, if you really want to, using the conditional operator:

var age = prompt("What's your age?");
(age < 1) ? alert("Infant") : (age < 13) ? alert("Child") : (age < 18) ? alert("Teenager") : alert("Adult");

Notice that for each conditional statement, I use the second option to introduce a new conditional operation, chaining them together. Again, some people will consider this completely unreadable, while others will love the efficiency of reducing all those lines of code to a single line. You are of course free to add some linebreaks, if you want to, in whatever way you feel would make it more readable. For instance, like this:

var age = prompt("What's your age?");
(age < 1) ? alert("Infant") 
		: (age < 13) ? alert("Child") 
		: (age < 18) ? alert("Teenager") 
		: alert("Adult");

Summary

The conditional/ternary operator allows you to do if..else statements in a shorter form, sometimes referred to as syntactic sugar. They are hated by some people who thinks that they make the code less readable, and loved by others for being short and concise. Use them if you want to!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!