What does the "?" and ":" do in this Code

If you wrote a simple if statement like:

if (val == 10) {
   x = 20;
} else {
   x = 15;
}

You could write the same code using the ternary operator as:

x = (val == 10) ? 20 : 15;

If the conditional expression (val == 10) is True, the expression following the question mark is evaluated. If the conditional expression is False, the expression following the colon is evaluated.

5 Likes