What is the ?: (question mark and colon operator aka. conditional or "ternary") operator and how can I use it?
What is the ?: (question mark and colon operator aka. conditional or "ternary") operator
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is a one-line shorthand for an if-else statement. It’s called the conditional operator.1
Here is an example of code that could be shortened with the conditional operator:
This can be shortened with the
?:like so:Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:
They can even be chained:
Be careful, though, or you will end up with convoluted code like this:
1 Often called “the ternary operator,” but in fact it’s just a ternary operator [an operator accepting three operands]. It’s the only one JavaScript currently has, though.