It accepts 3 operand and 2 operators. Here is syntax of ternary operator.
condition ? expression1 : expression2
From syntax above you can see that ternary operator contains 1 condition and 2 expressions. If condition evaluated is
true then expression1 is executed else expression2 is executed.
If...else VS ternary operator
Let's see an example and understand how convenient and easy it is to use the ternary operator. Using a ternary operator you can write clean code.
In the example below check if a student passed the exam if mark is greater than 40 than pass else fail.
Compare both conditional operators if...else and ternary.
Assigning a value using ternary operator
While using if...else you can set a value to some variable on some condition. You can do same using ternary operator and writing less code.
Nested Ternary Operator
Ternary operators can be nested to check multiple condition same as if...else but it becomes more complicated to read and also is not recomended.
First see code to find leap year using if...else statements.
Now let's see the same code using ternary operators.