Ternary Operator ?:

In this lesson, we will see what a ternary operator does and how we can use it in our code.

Ternary operator ?: #

The ?: operator works very similarly to an if-else statement:

if (/* condition check */) {
  /* ... expression(s) to execute if true */
} else {
  /* ... expression(s) to execute if false */
}

The if statement executes either the block for the case of true or the block for the case of false. As you remember, being a statement, it does not have a value; if merely affects the execution of code blocks.

On the other hand, the ?: operator is an expression. In addition to working similarly to the if-else statement, it produces a value. The equivalent of the above code is the following:

/* condition */ ? /* Expression if condition is true */ : /* Expression if condition is false */

Because it uses three expressions, the ?: operator is called the ternary operator.
The value that is produced by this operator is either the value of the truth expression or the value of the falsity expression. Because it is an expression, it can be used at any place where values are needed.

The following examples contrast the ?: operator to the if-else statement. The ternary operator is more concise and preferable to use in cases that are similar to these examples.

  • Initializating a value
    To initialize a variable with 366 if it is leap year, 365 otherwise:

Get hands-on with 1400+ tech skills courses.