Ternary Operator ?:
In this lesson, we will see what a ternary operator does and how we can use it in our code.
We'll cover the following...
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 ...
Access this course and 1400+ top-rated courses and projects.