The ternary operator(?:) is a conditional statement similar to the if-else statement. The format of using this operator is as follows:
For example:
x=(a>b)?y:z;
Here, if the condition (a>b) is true then:
x will be assigned the value y.
If the given condition is not true, i.e. a<b, then:
x will be assigned the value z.
Consider the following snippet of code. It checks whether the value of the variable flag is greater than 0 and assigns a value to the variable “alert” based on that.
if (flag>0){ alert="ON"; } else { alert="OFF"; }
This code can be written in just one line by using the ternary operator as follows:
alert=(flag>0)?"ON":"OFF";
To read more about this operator, you can go here.