The conditional ternary operator assigns a value to a variable based on some conditions. It is used in place of the if
statement. This operator also controls the flow of logical execution in the code
Note: The ternary operator is the onlydart
operator that takes 3 operators.
condition ? logicIfTrue : logicifFalse
condition
is the expression whose value determines the used value.?
is returned if the condition returns true
.:
is returned if the condition returns false
.Let's look at the code below:
import 'dart:convert';void main() {int score = 30;String output = score < 50 ? 'failed': 'Baby';print(output);}
import 'dart:convert';void main() {int score = 95;String output = score < 45 ? 'Failed': score == 45 ? 'Pass': 'Distinction';print(output);}
In the code above, we try to add grading to the student's score.
output
variable which we equate to the ternary operator. We also chain 2 conditions together. The first condition is score < 45
and we use the ?
to output the grade if the condition returns true. :
then we pass the condition score==45
. And we use the ?
to output the grade if the condition returns true. :
to return the default, assuming the 2 condition did not return true.output
variable.