# What is a ternary operator?

x ? y : z

A ternary operator is that question mark, followed by that colon. I think they’re freakin’ sweet! Its definition is as follows:

Ternary operator (Right associative). This operator acts as a short-hand for if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise, z is the result. Note that x cannot be null.

In Apex, this is really useful. It’s the equivalent of using an IF() formula in process builder or the Cloud Flow Designer. A very basic code example will illustrate the point.

``````String isItFive;

for (integer i = 0; i<10; i++) {

isItFive = i == 5 ? 'It\'s five' : 'It ain\'t five';

system.debug(isItFive);

}``````

The first line of code declares a string variable named isItFive.

Then we enter a loop. The loop declares an integer i and sets it’s value to 0. It checks if i is less than 10, and if it is, executes the code. After the code executes it increases the value of i by 1.

When the code executes we see the string variable that we declared earlier, isItFive, followed by an equal sign (an assignment operator). This means the code is attempting to set the value of isItFive using… a ternary operator!

As a Salesforce text formula it would read: isItFive = IF(i = 5, “It’s five”, “It ain’t five”)

The code executes ten times, entering the value of isItFive into the debug log each time. If you run this code in your Execute Anonymous window you’ll see the following result in the debug log:

Each time the code checked if i equaled 5. If it did not, it entered “It ain’t five” in the debug log. If it did, it entered “It’s five” in the debug log.

This can be a great time saver. A more practical example will illustrate this point.

Suppose you want to reassign a Task, based on its priority. You could use an If-Else clause to check the priority and assign it based on that value:

`for(Task t : taskList) {if(t.Priority == 'High') { t.OwnerId = // assign to User 1 by entering their userId here} else if (t.Priority == 'Medium') { t.OwnerId = // assign to User 2 by entering their userId here}`

… but we can do the same thing using the ternary operator!

`for(Task t : taskList) {t.OwnerId = t.Priority == 'High' ? t.OwnerId = 'User1' : t.OwerId = 'User2';}`

See how it simplifies things by reducing the lines of code we needed to write? Four lines of code down to one. Woohoo!

This site uses Akismet to reduce spam. Learn how your comment data is processed.