The JavaScript ternary operator is a useful tool that you’ll encounter in code quite often. Ternary operators can make statements more concise and easy to reason about. If the syntax is new to you, the operator may seem a little confusing. Let’s talk about the ternary operator and discuss some rules of thumb for how to use it.
What is the Ternary Operator
The JavaScript ternary operator is a single line control flow statement. You can think of it like a mini if/else statement. It contains 3 parts: the conditional, the truthy statement, and the falsy statement. Let’s look at a simple example then talk about how it works:
let age = 22; // The user's age // personType will be assigned the value "adult" let personType = age >= 18 ? "adult" : "child";
In the example, the conditional statement is age >= 18
. If that statement is a truthy expression, then the first statement (after the ?
but before the :
) will be the result of the ternary operation. If the conditional statement is falsy, then the second statement (after the :
) will be the result of the ternary operation. In the case of our example, personType
will be assigned the string "adult"
. We can write this code without a ternary operator:
let age = 22; // The user's age let personType; if (age >= 18) { personType = "adult"; } else { personType = "child"; }
The two examples achieve the same goal, but our ternary operator example is much more concise. In your programming career, you’ll encounter ternary operators often for simple one line statements.
Best Practice: Don’t Use Nested Ternaries
If you’re just getting used to ternary operators in JavaScript, you might have the urge to use them as much as possible. But a simple rule that I have for student’s code as well as my own code is not to make your ternary operators too complex. For example, you should not try to make ternary operators nested inside of ternary operators. Although writing code this way works correctly in JavaScript, it is very hard to read and understand. You should always think about someone looking at your code a year or two from now and wonder: “will this person be able to figure out what this line of code is doing?” I would argue that having a nested ternary will definitely make it hard on that future coder.
Let’s look at an example of how a nested ternary works and then we can talk about an easier (and better) way to write the same code:
// A task has a description an priority let task = {description: "Do laundry", priority: 3}; // We want a color to represent the task priority // lower numbers are high priority (red), and // larger numbers are lower priority let taskColor = task.priority === 1 ? "red" : task.priority === 2 ? "yellow" : "green";
This is an example of a nested ternary and I think it’s fair to say that you might be confused what is going to be returned for taskColor. It might be a little easier to visualize this if we add parenthesis:
let taskColor = task.priority === 1 ? ("red") : (task.priority === 2 ? "yellow" : "green");
The value "red"
is the truthy result of the outer ternary. If task.priority is 1, then the result is "red"
and we don’t need to worry about the 2nd ternary operator. If task.priority is not 1, then the 2nd ternary goes into action. Whatever the 2nd ternary evaluates to is our answer. This is just a simple example but it’s easy to see how this can get confusing. My advice: do not use nested ternary statements.
An easy fix to this problem is to convert it to if/else if statements. Using if statements requires more lines of code, but readability is always more important:
// A task has a description an priority let task = {description: "Do laundry", priority: 3}; // We want a color to represent the task priority // lower numbers are high priority (red), and // larger numbers are lower priority (green) // green is the default task color let taskColor = "green"; if (task.priority === 1) { taskColor = "red"; } else if (task.priority === 2) { taskColor = "yellow"; }
Best Practice: Don’t Do Assignments Inside Ternaries
Another issue I see often with student’s code is the use of assignments inside of ternary operators. It’s best to avoid this since the code can be confusing to read. Here is an example of what I’m talking about:
let message = ""; let hobbies = ["sailing", "biking", "coding"]; hobbies.includes("baking") ? message = "hobby found!" : message = "hobby not found";
In the above example, we are assigning to a message
variable depending on the conditional expression in the ternary. If the hobbies array includes "baking"
, then the message variable is assigned "hobby found"
and if the hobbies array does not include "baking"
, then message is assigned "hobby not found"
. So the best practice here is do not do an assignment inside of the ternary operator. Instead, the code can be simplified by doing the assignment afterwords. We should prefer to write the code so that the assignment happens after the ternary is resolved:
let hobbies = ["sailing", "biking", "coding"]; let message = hobbies.includes("baking") ? "hobby found!" : "hobby not found";
The above code is more readable. It’s easier to see that an assignment is happening. It is also less code to type.
Conclusion
The ternary operator is a common tool that you’ll see a lot in JavaScript code. It can make your code concise but it can also make your code unreadable if you don’t use it properly. Try to keep the ternaries simple and readable. Make sure to follow the best practices in this blog post and good luck!