Ternary Operator in Dart Programming


The ternary operator is a shorthand version of an if-else condition. There are two types of ternary operator syntax in Dart, one with a null safety check and the other is the same old one we encounter normally.

Syntax 1

condition ? expressionOne : expressionTwo;

The above syntax implies that if a certain condition evaluates to true then we evaluate the expressionOne first and then the expressionTwo.

Example

Let's explore a Dart example where we make use of the above syntax of the ternary operator.

Consider the example shown below −

 Live Demo

void main(){
   var ans = 10;
   ans == 10 ? print("Answer is 10") : print("Oh no!");
}

In the above example, we declared a variable named ans with a value 10, and then in the next line, we have a condition of the ternary operator where we are checking if it is equal to 10. If so, then evaluate the first expression else evaluate the expression after the colon (:).

Output

Answer is 10

Syntax 2

expression1 ?? expression2

It depicts a conditional statement that is similar to a ternary operator statement. The only difference is that in the above syntax if expression1 is not null, then it gets evaluated else expression2 is evaluated.

Example

Consider the example shown below −

void main(){
   var ans;
   ans ?? print("ans is null");
}

Output

ans is null

Updated on: 24-May-2021

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements