Ternary operator / Question mark and colon in JavaScript
“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands.
- The expression consists of three operands: the condition, value if true and value if false.
- The evaluation of the condition should result in either true/false or a boolean value.
- The true value lies between “?” & “:” and is executed if the condition returns true. Similarly, the false value lies after “:” and is executed if the condition returns false.
Syntax:
condition ? value if true : value if false
- condition:
- Expression to be evaluated which returns a boolean value.
- Value to be executed if condition results in true state.
- Value to be executed if condition results in false state.
value if true:
value if false:
Examples:
Input: let result = (10 > 0) ? true : false; Output: true Input: let message = (20 > 15) ? "Yes" : "No"; Output: Yes
The following programs will illustrate conditional operator more extensively:
Program 1:
<script> //JavaScript to illustrate //Conditional operator let age = 60 let result = (age > 59)? "Senior Citizen":"Not a Senior Citizen"; alert(result); </script> |
chevron_right
filter_none
Output:
Senior Citizen
An example of multiple conditional operators.
Program 2:
<script> //JavaScript to illustrate //multiple Conditional operators let marks = 95; let result = (marks < 40) ? "Unsatisfactory" : (marks < 60) ? "Average" : (marks < 80) ? "Good" : "Excellent" ; alert(result); </script> |
chevron_right
filter_none
Output:
Excellent
Recommended Posts:
- Ternary operator vs Null coalescing operator in PHP
- JavaScript Course | Conditional Operator in JavaScript
- What is the !! (not not) operator in JavaScript?
- Arrow operator in ES6 of JavaScript
- Difference between != and !== operator in JavaScript
- Difference between == and === operator in JavaScript
- JavaScript | ‘===’ vs ‘==’Comparison Operator
- Instanceof operator in JavaScript
- JavaScript | Spread Operator
- JavaScript | typeof operator
- How to get negative result using modulo operator in JavaScript ?
- HTML5 | mark Tag
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- HTML | DOM Mark Object
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


