If you have ever been looking at JavaScript code and wondered what the heck the ?
and :
is doing, look no further!
These two characters (?:) when used together is collectively called the ternary conditional operator, or ternary for short. It is used to express a basic conditional operation, in the form:
predicate ? truthy : falsey
The operand that comes before the ?
is the predicate, or the expression that you are basing your decision logic on. The expression that follows the ?
will be what is executed if the predicate is true. The expression after the :
is what is executed if the predicate is false
Example
Lets imagine you have an object that represents a user
, and it potentially has a key username
that would store that users username. If we wanted to determine what to display in the UI, we could decide to show the username if it exists, or Anonymous if it does not. We can quickly create a variable called username that will hold the correct value:
const username = user.username ? user.username : 'Anonymous';
This would be opposed to writing the same functionality with a traditional if
statement:
let username;
if (user.username) {
username = user.username;
} else {
username = 'Anonymous';
}
Of course, the two expressions after the ?
can be anything that evaluates to a value:
const someVal = checkSomething() ? doCoolThingSinceTrue() : doOtherLogicSinceFalse();
Suggestions
This part is opinionated, but I try to avoid using multiple ternary operators chained together. Nothing stops you from doing:
const res = check() ? (checkTwo ? 'true checkTwo' : 'false checkTwo') : 'false check';
but in my opinion this causes more confusion than clarity and it would be better to write it in a more traditional if/else structure.
I usually prefer ternary if it is a quick 'inline' computation that I am passing as a parameter, or like in the original example, I am picking one of two expressions to execute at runtime and I need the result.
Conclusion
Hopefully that helps clear up what this operator is all about and how it can be used. If you have any questions, feel free to ask them below!
Top comments (1)
Absolutely! This is a great call out, as it also extracts some functionality into a nice, named, testable piece of code!
Thanks for the comment 😊