It is the ternary operator/conditional operator.
In mathematics, a ternary operation is an n-ary operation with n = 3. A ternary operation on a set A takes any given three elements of A and combines them to form a single element of A.
It is a short hand form of if..else.
E.g., to want to find out if a number is even or not.
Using the if..else approach
function CheckEvenOdd()
{
var number = 2;
if(number % 2 == 0)
alert("even");
else
alert("odd");
}
Using ternary
function CheckEvenOdd()
{
var number = 2;
alert((number %2 == 0) ? "even" : "odd");
}
Using switch
One more variant is switch:
function CheckEvenOdd()
{
var number = 2;
switch(number % 2)
{
case 0:
alert("even");
break;
default:
alert("odd");
break;
}
}
Now, if you have a simple if..else condition to perform like the one described, you can go ahead with ternary.
But if the conditional checking becomes complex, go either with if..else or switch as readability will be lost in ternary.
For example, it is easy to get the minimum or maximum of two numbers using a ternary operator, but it becomes clumsy to find the largest and second largest among three or more numbers and is not even recommended. It is better to use if..else instead.