Learn
Conditional Statements
Ternary Operator
The ternary operator is a concise way to write simple conditional statements. It provides a compact syntax for making decisions based on a condition.
Syntax
The syntax for the ternary operator is as follows:
The condition
is evaluated and if it is true, expression1
is executed. If the condition is false, expression2
is executed.
Example
Consider the following code snippet:
In this example, we use the ternary operator to check if the age
variable is greater than or equal to 18. If it is, the value of greeting
will be "Welcome, adult!". If not, the value will be "Sorry, you must be 18 or older.". The result is then printed to the console.
The ternary operator can be nested, allowing for more complex conditions and expressions. However, be cautious not to make it too complex, as it may reduce the readability of your code.
Instructions
Declare a variable result
and assign it the value of "Yes"
if isTrue
is true, otherwise assign it the value of "No"
, using the ternary operator.
Sign up to start coding
Already have an account?
Sign In